Converting int into NSString [duplicate]

心不动则不痛 提交于 2019-12-17 22:38:31

问题


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.


回答1:


If you want to change the int to string

NSString *strFromInt = [NSString stringWithFormat:@"%d",yourintvalue];



回答2:


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, ...).




回答3:


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);



回答4:


You have used NSLog statement incorrectly.It should have been used like below.

NSLog(@"%@",unique);



来源:https://stackoverflow.com/questions/12153051/converting-int-into-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!