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";
213476 次浏览

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

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

If you just need an int to a string as you suggest, I've found the easiest way is to do as below:

[NSString stringWithFormat:@"%d",numberYouAreTryingToConvert]
int val1 = [textBox1.text integerValue];
int val2 = [textBox2.text integerValue];


int resultValue = val1 * val2;


textBox3.text = [NSString stringWithFormat: @"%d", resultValue];

You can use literals, it's more compact.

NSString* myString = [@(17) stringValue];

(Boxes as a NSNumber and uses its stringValue method)

Simply convert int to NSString use :

  int x=10;


NSString *strX=[NSString stringWithFormat:@"%d",x];

Dot grammar maybe more swift!

@(intValueDemo).stringValue

for example

int intValueDemo  = 1;
//or
NSInteger intValueDemo = 1;


//So you can use dot grammar
NSLog(@"%@",@(intValueDemo).stringValue);