Shortcuts in Objective-C to concatenate NSStrings

Shortcuts in Objective-C to concatenate NSStrings

b’

An option:

n

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

n

Another option:

n

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

n

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

n

using something like

n

+ (NSString *) append:(id) first, ...n{n    NSString * result = @;n    id eachArg;n    va_list alist;n    if(first)n    {n        result = [result stringByAppendingString:first];n        va_start(alist, first);n        while (eachArg = va_arg(alist, id)) n        result = [result stringByAppendingString:eachArg];n        va_end(alist);n    }n    return result;n}n

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

n

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

n

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:

n

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

n

Thats also useful for joining #defines:

n

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

n

Enjoy.

Leave a Reply

Your email address will not be published.