Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"; 
like image 428
john Avatar asked Jul 09 '09 15:07

john


People also ask

What is %s in Objective-C?

Remember: %s is for C strings, %@ is for Objective-C objects.

What does @() mean in Objective-C?

It's Shorthand writing. In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals.


1 Answers

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] 
like image 55
Scott Avatar answered Sep 19 '22 13:09

Scott