Shortcuts in Objective-C to concatenate NSStrings

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

For example, I’d like to make:

NSString *myString = @"This";
NSString *test = [myString stringByAppendingString:@" is just a test"];

something more like:

string myString = "This";
string test = myString + " is just a test";

30
30

An option:

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

Another option:

I’m guessing you’re 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, @"https://stackoverflow.com/", two, @"https://stackoverflow.com/", 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;
}

Leave a Comment