Shortcuts in Objective-C to concatenate NSStrings

Shortcuts in Objective-C to concatenate NSStrings

An option:

[NSString stringWithFormat:@%@/%@/%@, one, two, three];

Another option:

Im guessing youre not happy with multiple appends (a+b+c+d), in which case you could do:

NSLog(@%@, [Util append:one, @ , two, nil]); // one two
NSLog(@%@, [Util append:three, @/, two, @/, one, nil]); // three/two/one

using something like

+ (NSString *) append:(id) first, ...
{
    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);
    }
    return result;
}

Two answers I can think of… neither is particularly as pleasant as just having a concatenation operator.

First, use an NSMutableString, which has an appendString method, removing some of the need for extra temp strings.

Second, use an NSArray to concatenate via the componentsJoinedByString method.

Shortcuts in Objective-C to concatenate NSStrings

If you have 2 NSString literals, you can also just do this:

NSString *joinedFromLiterals = @ONE  @MILLION  @YEARS  @DUNGEON!!!;

Thats also useful for joining #defines:

#define STRINGA @Also, I dont know 
#define STRINGB @where food comes from.
#define JOINED STRINGA STRINGB

Enjoy.

Leave a Reply

Your email address will not be published. Required fields are marked *