如何将 int 转换为 NSString?

我想把目标 C 中的 int转换成 NSString

我怎么能这么做?

157374 次浏览
NSString *string = [NSString stringWithFormat:@"%d", theinteger];
int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];

This is one of many ways.

Primitives can be converted to objects with @() expression. So the shortest way is to transform int to NSNumber and pick up string representation with stringValue method:

NSString *strValue = [@(myInt) stringValue];

or

NSString *strValue = @(myInt).stringValue;

If this string is for presentation to the end user, you should use NSNumberFormatter. This will add thousands separators, and will honor the localization settings for the user:

NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];

In the US, for example, that would create a string 10,000, but in Germany, that would be 10.000.