在Objective-C中有没有(stringByAppendingString:)字符串连接的快捷方式,或者一般使用NSString的快捷方式?

例如,我想做:

NSString *myString = @"This";
NSString *test = [myString stringByAppendingString:@" is just a test"];

更像是:

string myString = "This";
string test = myString + " is just a test";

当前回答

NSString *myString = @"This";
NSString *test = [myString stringByAppendingString:@" is just a test"];

在使用Objective C几年之后,我认为这是使用Objective C实现你想要实现的目标的最佳方式。

开始在你的Xcode应用中输入“N”,它自动完成为“NSString”。 key in "str",它自动补全为"stringByAppendingString"。所以按键是非常有限的。

一旦你掌握了敲击“@”键和标签的窍门,编写可读代码的过程就不再是问题了。这只是一个适应的问题。

其他回答

NSString *label1 = @"Process Name: ";
NSString *label2 = @"Process Id: ";
NSString *processName = [[NSProcessInfo processInfo] processName];
NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
NSString *testConcat = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];

如果你有两个NSString字面量,你也可以这样做:

NSString *joinedFromLiterals = @"ONE " @"MILLION " @"YEARS " @"DUNGEON!!!";

这对于加入#定义也很有用:

#define STRINGA @"Also, I don't know "
#define STRINGB @"where food comes from."
#define JOINED STRINGA STRINGB

享受。

当为web服务构建请求时,我发现像下面这样做非常容易,并且在Xcode中使连接可读:

NSString* postBody = {
    @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    @"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
    @" <soap:Body>"
    @"  <WebServiceMethod xmlns=\"\">"
    @"   <parameter>test</parameter>"
    @"  </WebServiceMethod>"
    @" </soap:Body>"
    @"</soap:Envelope>"
};

如何缩短stringByAppendingString和使用#define:

#define and stringByAppendingString

因此你可以使用:

NSString* myString = [@"Hello " and @"world"];

问题是它只适用于两个字符串,你需要包装额外的括号更多的追加:

NSString* myString = [[@"Hello" and: @" world"] and: @" again"];

尝试stringWithFormat:

NSString *myString = [NSString stringWithFormat:@"%@ %@ %@ %d", "The", "Answer", "Is", 42];