Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString is integer?

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;   } } 
like image 580
Carlos Barbosa Avatar asked Feb 19 '09 15:02

Carlos Barbosa


People also ask

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

How to convert string to integer in objective c?

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");

Do I need to release NSString?

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.


2 Answers

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.

like image 178
Stephen Darlington Avatar answered Sep 29 '22 04:09

Stephen Darlington


Something like this:

NSScanner* scan = [NSScanner scannerWithString:toCheck];  int val;  return [scan scanInt:&val] && [scan isAtEnd]; 
like image 33
Steven Green Avatar answered Sep 29 '22 02:09

Steven Green