A common issue: parsing user input that may need to be recognized as a number in code. This is done relatively easily using NSScanner and will not cause a crash should invalid data be entered, leaving a way to easily alert a user of the problem.

By Example

To understand how this works I’ve posted an example of how one would validate a GPS coordinate (comprises of two doubles, latitude and longitude) and convert it to an actual number in code.

//USER INPUT
NSString* userInputLat = @"-105.555";
NSString* userInputLon = @"55.555";

//Parse code begins
double lat, lon;
CLLocationCoordinate2D gpsCoord;
NSString* error = @"";

NSScanner *scanner = [NSScanner scannerWithString:userInputLat];
BOOL latSuccess = [scanner scanDouble:&lat];

scanner = [NSScanner scannerWithString:userInputLon];
BOOL lonSuccess = [scanner scanDouble:&lon];

if(!latSuccess)
	error = [error stringByAppendingString:@"Invalid latitude entered\n"];
if(!lonSuccess)
	error = [error stringByAppendingString:@"Invalid latitude entered\n"];

if([error length] > 0){
	// code to alert user...
}
else{
	//We can safely use the user input
	gpsCoord.latitude = lat;
	gpsCoord.longitude = lon;

	//Perform calculations...
}

Note that this will work with float, integer, etc just by changing the [scanner scan{TYPE}] function call.

No Comments

There are no comments related to this article.