Shortcuts in Objective-C to concatenate NSStrings
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, @"/", 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.
If you have 2 NSString literals, you can also just do this:
NSString *joinedFromLiterals = @"ONE " @"MILLION " @"YEARS " @"DUNGEON!!!";
That's also useful for joining #defines:
#define STRINGA @"Also, I don't know "
#define STRINGB @"where food comes from."
#define JOINED STRINGA STRINGB
Enjoy.
I keep returning to this post and always end up sorting through the answers to find this simple solution that works with as many variables as needed:
[NSString stringWithFormat:@"%@/%@/%@", three, two, one];
For example:
NSString *urlForHttpGet = [NSString stringWithFormat:@"http://example.com/login/username/%@/userid/%i", userName, userId];