john john - 6 months ago 29
Objective-C Question

How to convert from int to string in objective c: example code

I am trying to convert from an int to a string but I am having trouble. I followed the execution through the debugger and the string 'myT' gets the value of 'sum' but the 'if' statement does not work correctly if the 'sum' is 10,11,12. Should I not be using a primitive int type to store the number? Also, both methods I tried (see commented-out code) fail to follow the true path of the 'if' statement. Thanks!

int x = [my1 intValue];
int y = [my2 intValue];
int sum = x+y;
//myT = [NSString stringWithFormat:@"%d", sum];
myT = [[NSNumber numberWithInt:sum] stringValue];

if(myT==@"10" || myT==@"11" || myT==@"12")
action = @"numGreaterThanNine";


The commented out version is the more correct way to do this.

If you use the == operator on strings, you're comparing the strings' addresses (where they're allocated in memory) rather than the values of the strings. This is very occasional useful (it indicates you have the exact same string object), but 99% of the time you want to compare the values, which you do like so:

if([myT isEqualToString:@"10"] || [myT isEqualToString:@"11"] || [myT isEqualToString:@"12"])