Question

I am converting a string to signed integer via NSScanner:scanInteger, but it seems to be accepting values such as '123abc' as '123', instead of throwing a error on invalid input.

I can do my own custom validation, but would prefer to find an API which will do the conversion and fail on '123abc'.

By the way, 'abc123' does fail with scanInteger, which is good.

Was it helpful?

Solution

I don't think that using a scanner is the way to do this -- you could, but there are easier ways. I would use the NSString method rangeOfCharactersFromSet: to check for non-digit characters.

NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSUInteger nonDigits = [enteredString rangeOfCharacterFromSet:notDigits].length;

If nonDigits is not zero, then the user has entered something other than a digit. If you want to allow decimal points then you would have to create your own set that contains everything other than digits and the decimal point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top