How to check if the content of a NSString is an integer value? Is there any readily available way?
There got to be some better way then doing something like this:
- (BOOL)isInteger:(NSString *)toCheck { if([toCheck intValue] != 0) { return true; } else if([toCheck isEqualToString:@"0"]) { return true; } else { return false; } }
A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.
6 int answer = [@"42" intValue]; 7 NSString *answerString = 8 [NSString stringWithFormat: @"%d", answer]; 9 NSNumber *boxedAnswer = 10 [NSNumber numberWithInt: answer]; 11 NSCAssert([answerString isEqualToString: 12 [boxedAnswer stringValue]], 13 @"Both strings should be the same");
If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.
You could use the -intValue
or -integerValue
methods. Returns zero if the string doesn't start with an integer, which is a bit of a shame as zero is a valid value for an integer.
A better option might be to use [NSScanner scanInt:]
which returns a BOOL
indicating whether or not it found a suitable value.
Something like this:
NSScanner* scan = [NSScanner scannerWithString:toCheck]; int val; return [scan scanInt:&val] && [scan isAtEnd];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With