Shortcuts in Objective-C to concatenate NSStrings

前端 未结 30 2649
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 07:03

Are there any shortcuts to (stringByAppendingString:) string concatenation in Objective-C, or shortcuts for working with NSString in general?

30条回答
  •  死守一世寂寞
    2020-11-22 07:47

    Macro:

    // 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:@""]
    

    Test Cases:

    - (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");
    }
    

    Alternate macro: (if you wanted to enforce a minimum number of arguments)

    // 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:@""];
    

提交回复
热议问题