Shortcuts in Objective-C to concatenate NSStrings

前端 未结 30 2602
伪装坚强ぢ
伪装坚强ぢ 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:52

    Here's a simple way, using the new array literal syntax:

    NSString * s = [@[@"one ", @"two ", @"three"] componentsJoinedByString:@""];
                      ^^^^^^^ create array ^^^^^
                                                   ^^^^^^^ concatenate ^^^^^
    
    0 讨论(0)
  • 2020-11-22 07:52

    Try stringWithFormat:

    NSString *myString = [NSString stringWithFormat:@"%@ %@ %@ %d", "The", "Answer", "Is", 42];
    
    0 讨论(0)
  • 2020-11-22 07:54

    Inspired by NSMutableString idea from Chris, I make a perfect macro imho.

    #import <libextobjc/metamacros.h>
    
    #define STR_CONCAT(...) \
        ({ \
            __auto_type str__ = [NSMutableString string]; \
            metamacro_foreach_cxt(never_use_immediately_str_concatify_,, str__, __VA_ARGS__) \
            (NSString *)str__.copy; \
        })
    
    #define never_use_immediately_str_concatify_(INDEX, CONTEXT, VAR) \
        [CONTEXT appendString:VAR ?: @""];
    

    Example:

    STR_CONCAT(@"button_bg_", @(count).stringValue, @".png"); 
    // button_bg_2.png
    

    If you like, you can use id type as parameter by using [VAR description] instead of NSString.

    0 讨论(0)
  • 2020-11-22 07:55
    NSString *result=[NSString stringWithFormat:@"%@ %@", @"Hello", @"World"];
    
    0 讨论(0)
  • 2020-11-22 07:57
    NSString *myString = @"This";
    NSString *test = [myString stringByAppendingString:@" is just a test"];
    

    After a couple of years now with Objective C I think this is the best way to work with Objective C to achieve what you are trying to achieve.

    Start keying in "N" in your Xcode application and it autocompletes to "NSString". key in "str" and it autocompletes to "stringByAppendingString". So the keystrokes are quite limited.

    Once you get the hang of hitting the "@" key and tabbing the process of writing readable code no longer becomes a problem. It is just a matter of adapting.

    0 讨论(0)
  • 2020-11-22 07:57
    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];
    
    0 讨论(0)
提交回复
热议问题