连接NSString和int的最简单方法

时间:2009-04-01 01:11:08

标签: objective-c string cocoa cocoa-touch nsstring

Objective-C中是否有一个通用函数可以插入到我的项目中以简化NSStringint的连接?

5 个答案:

答案 0 :(得分:33)

[NSString stringWithFormat:@"THIS IS A STRING WITH AN INT: %d", myInt];

这通常就是我的做法。

答案 1 :(得分:29)

两个答案都是正确的。如果要连接多个字符串和整数,请使用NSMutableString的appendFormat。

NSMutableString* aString = [NSMutableString stringWithFormat:@"String with one int %d", myInt];    // does not need to be released. Needs to be retained if you need to keep use it after the current function.
[aString appendFormat:@"... now has another int: %d", myInt];

答案 2 :(得分:3)

NSString *s = 
   [
       [NSString alloc] 
           initWithFormat:@"Concatenate an int %d with a string %@", 
            12, @"My Concatenated String"
   ];

我知道你可能正在寻找一个更短的答案,但这就是我要用的。

答案 3 :(得分:3)

string1,x,它们分别声明为字符串对象和整数变量。如果要组合这两个值并将int值附加到字符串对象并将结果分配给新字符串,请执行以下操作。

NSString *string1=@"Hello"; 

int x=10;

NSString *string2=[string1 stringByAppendingFormat:@"%d ",x];

NSLog(@"string2 is %@",string2);


//NSLog(@"string2 is %@",string2); is used to check the string2 value at console ;

答案 4 :(得分:-1)

似乎真正的答案是否定的 - 没有简单的方法将NSStrings与Objective C连接起来 - 与在C#和Java中使用'+'运算符没什么相似。