Are there any shortcuts to (stringByAppendingString:
) string concatenation in Objective-C, or shortcuts for working with NSString
in general?
Here's a simple way, using the new array literal syntax:
NSString * s = [@[@"one ", @"two ", @"three"] componentsJoinedByString:@""];
^^^^^^^ create array ^^^^^
^^^^^^^ concatenate ^^^^^
Try stringWithFormat:
NSString *myString = [NSString stringWithFormat:@"%@ %@ %@ %d", "The", "Answer", "Is", 42];
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
.
NSString *result=[NSString stringWithFormat:@"%@ %@", @"Hello", @"World"];
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.
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];