Are there any shortcuts to (stringByAppendingString:
) string concatenation in Objective-C, or shortcuts for working with NSString
in general?
You can use NSArray as
NSString *string1=@"This"
NSString *string2=@"is just"
NSString *string3=@"a test"
NSArray *myStrings = [[NSArray alloc] initWithObjects:string1, string2, string3,nil];
NSString *fullLengthString = [myStrings componentsJoinedByString:@" "];
or
you can use
NSString *imageFullName=[NSString stringWithFormat:@"%@ %@ %@.", string1,string2,string3];
The only way to make c = [a stringByAppendingString: b]
any shorter is to use autocomplete at around the st
point. The +
operator is part of C, which doesn't know about Objective-C objects.
[NSString stringWithFormat:@"%@/%@/%@", one, two, three];
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;
}
Create a method:
- (NSString *)strCat: (NSString *)one: (NSString *)two
{
NSString *myString;
myString = [NSString stringWithFormat:@"%@%@", one , two];
return myString;
}
Then, in whatever function you need it in, set your string or text field or whatever to the return value of this function.
Or, to make a shortcut, convert the NSString into a C++ string and use the '+' there.
Either of these formats work in XCode7 when I tested:
NSString *sTest1 = {@"This" " and that" " and one more"};
NSString *sTest2 = {
@"This"
" and that"
" and one more"
};
NSLog(@"\n%@\n\n%@",sTest1,sTest2);
For some reason, you only need the @ operator character on the first string of the mix.
However, it doesn't work with variable insertion. For that, you can use this extremely simple solution with the exception of using a macro on "cat" instead of "and".
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];