在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";
这是为了更好的日志记录,而且仅仅是日志记录——基于dicius优秀的多参数方法。我定义了一个Logger类,并像这样调用它:
[Logger log: @"foobar ", @" asdads ", theString, nil];
几乎很好,除了var args必须以“nil”结束,但我想在Objective-C中没有办法绕过它。
Logger.h
@interface Logger : NSObject {
}
+ (void) log: (id) first, ...;
@end
Logger.m
@implementation Logger
+ (void) log: (id) first, ...
{
// TODO: make efficient; handle arguments other than strings
// thanks to @diciu http://stackoverflow.com/questions/510269/how-do-i-concatenate-strings-in-objective-c
NSString * result = @"";
id eachArg;
va_list alist;
if(first)
{
result = [result stringByAppendingString:first];
va_start(alist, first);
while (eachArg = va_arg(alist, id))
{
result = [result stringByAppendingString:eachArg];
}
va_end(alist);
}
NSLog(@"%@", result);
}
@end
为了只连接字符串,我在NSString上定义了一个Category,并添加了一个静态(+)连接方法,它看起来完全像上面的log方法,除了它返回字符串。它在NSString上,因为它是一个字符串方法,它是静态的,因为你想从1-N个字符串中创建一个新字符串,而不是在任何一个作为append一部分的字符串上调用它。
这样使用stringByAppendingString:
NSString *string1, *string2, *result;
string1 = @"This is ";
string2 = @"my string.";
result = [result stringByAppendingString:string1];
result = [result stringByAppendingString:string2];
OR
result = [result stringByAppendingString:@"This is "];
result = [result stringByAppendingString:@"my string."];