Objective-c convert NSString into NSInteger
Do:
NSString *str = @"3 568 030";
int aValue = [[str stringByReplacingOccurrencesOfString:@" " withString:@""] intValue];
NSLog(@"%d", aValue);
output
3568030
That is because of the spaces on your string you will have to remove the whitespaces first like this:
NSString *trimmedString = [myString stringByReplacingOccurrencesOfString:@" " withString:@""];
NSInteger *value = [trimmedString intValue];
My guess is that you're using stringByReplacingOccurencesOfString::
wrongly.
//Remove spaces.
myString = [myString stringByReplacingOccurencesOfString:@" " withString @""];
int myNumber = [myString intValue];
First, remove all the whitespaces in your original string using :
NSString *trimmedString = [yourOriginalString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Then, you can convert it to an int/NSInteger. beware: using [myString intValue]
will cast your string to an int, but [myString integerValue]
will cast it to a NSInteger.
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:@"42"];
[f release];
精彩评论