views:

12833

answers:

2

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";
+4  A: 

"==" shouldn't be used to compare objects in your if. For NSString use isEqualToString: to compare them.

Terry Wilcox
+6  A: 

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"])
grahamparks
Slight typo, a missing : in the 2nd comparison.
marcc