宏:
// stringConcat(...)
// A shortcut for concatenating strings (or objects' string representations).
// Input: Any number of non-nil NSObjects.
// Output: All arguments concatenated together into a single NSString.
#define stringConcat(...) \
[@[__VA_ARGS__] componentsJoinedByString:@""]
测试用例:
- (void)testStringConcat {
NSString *actual;
actual = stringConcat(); //might not make sense, but it's still a valid expression.
STAssertEqualObjects(@"", actual, @"stringConcat");
actual = stringConcat(@"A");
STAssertEqualObjects(@"A", actual, @"stringConcat");
actual = stringConcat(@"A", @"B");
STAssertEqualObjects(@"AB", actual, @"stringConcat");
actual = stringConcat(@"A", @"B", @"C");
STAssertEqualObjects(@"ABC", actual, @"stringConcat");
// works on all NSObjects (not just strings):
actual = stringConcat(@1, @" ", @2, @" ", @3);
STAssertEqualObjects(@"1 2 3", actual, @"stringConcat");
}
备用宏:(如果你想强制一个最小数量的参数)
// stringConcat(...)
// A shortcut for concatenating strings (or objects' string representations).
// Input: Two or more non-nil NSObjects.
// Output: All arguments concatenated together into a single NSString.
#define stringConcat(str1, str2, ...) \
[@[ str1, str2, ##__VA_ARGS__] componentsJoinedByString:@""];