Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting int into NSString [duplicate]

I want to convert a random int number in the NSString and then assign the NSString to another NSString but it crashes the app

I am doing the following

int mynumber =(arc4random() % 1000 );

unique = [NSString stringWithFormat:@"%d",mynumber];

   NSLog(unique)

   NSString*test=unique;

it gives crash when i write last line;

It also prints values when I nslog the unique string.

like image 386
user1619187 Avatar asked Aug 28 '12 05:08

user1619187


3 Answers

If you want to change the int to string

NSString *strFromInt = [NSString stringWithFormat:@"%d",yourintvalue]; 
like image 85
Tendulkar Avatar answered Sep 25 '22 12:09

Tendulkar


This also works:

NSString *str = [@(number) stringValue];

Or, if you prefer dot notation:

NSString *str = @(number).stringValue;

This will box the primitive value to a NSNumber using the expression boxing syntax @(...), then use its' stringValue method to convert it to NSString. This should also work for other primitive values (NSInteger, float, double, long, ...).

like image 28
d4n3 Avatar answered Sep 21 '22 12:09

d4n3


NSString *anotherStr;
int myNumber = (arc4random() % 1000 );
NSString *stringNum = [NSString stringWithFormat:@"%i", myNumber];
anotherStr = stringNum; //assign NSString to NSString
// Here you can convert NSString to Int if you want.
NSLog(@"My number as NSString = %@", stringNum);
int getNumFromString = [stringNum intValue];

NSLog(@"My number from NSString = %i", getNumFromString);
like image 41
Pandey_Laxman Avatar answered Sep 25 '22 12:09

Pandey_Laxman