那么,结肠癌是一种特殊的符号,但是是方法签名的一部分,有可能加长的NSString
类别为添加这个非惯用的字符串连接的风格:
[@"This " : @"feels " : @"almost like " : @"concatenation with operators"];
您可以定义尽可能多的用冒号分隔的参数... ;-)
作为一项很好的措施,我还添加了concat:
带有nil
终止字符串列表的可变参数。
// NSString+Concatenation.h
#import <Foundation/Foundation.h>
@interface NSString (Concatenation)
- (NSString *):(NSString *)a;
- (NSString *):(NSString *)a :(NSString *)b;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d;
- (NSString *)concat:(NSString *)strings, ...;
@end
// NSString+Concatenation.m
#import "NSString+Concatenation.h"
@implementation NSString (Concatenation)
- (NSString *):(NSString *)a { return [self stringByAppendingString:a];}
- (NSString *):(NSString *)a :(NSString *)b { return [[self:a]:b];}
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c
{ return [[[self:a]:b]:c]; }
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d
{ return [[[[self:a]:b]:c]:d];}
- (NSString *)concat:(NSString *)strings, ...
{
va_list args;
va_start(args, strings);
NSString *s;
NSString *con = [self stringByAppendingString:strings];
while((s = va_arg(args, NSString *)))
con = [con stringByAppendingString:s];
va_end(args);
return con;
}
@end
// NSString+ConcatenationTest.h
#import <SenTestingKit/SenTestingKit.h>
#import "NSString+Concatenation.h"
@interface NSString_ConcatenationTest : SenTestCase
@end
// NSString+ConcatenationTest.m
#import "NSString+ConcatenationTest.h"
@implementation NSString_ConcatenationTest
- (void)testSimpleConcatenation
{
STAssertEqualObjects([@"a":@"b"], @"ab", nil);
STAssertEqualObjects([@"a":@"b":@"c"], @"abc", nil);
STAssertEqualObjects([@"a":@"b":@"c":@"d"], @"abcd", nil);
STAssertEqualObjects([@"a":@"b":@"c":@"d":@"e"], @"abcde", nil);
STAssertEqualObjects([@"this " : @"is " : @"string " : @"concatenation"],
@"this is string concatenation", nil);
}
- (void)testVarArgConcatenation
{
NSString *concatenation = [@"a" concat:@"b", nil];
STAssertEqualObjects(concatenation, @"ab", nil);
concatenation = [concatenation concat:@"c", @"d", concatenation, nil];
STAssertEqualObjects(concatenation, @"abcdab", nil);
}