Are there any shortcuts to (stringByAppendingString:
) string concatenation in Objective-C, or shortcuts for working with NSString
in general?
My preferred method is this:
NSString *firstString = @"foo";
NSString *secondString = @"bar";
NSString *thirdString = @"baz";
NSString *joinedString = [@[firstString, secondString, thirdString] join];
You can achieve it by adding the join method to NSArray with a category:
#import "NSArray+Join.h"
@implementation NSArray (Join)
-(NSString *)join
{
return [self componentsJoinedByString:@""];
}
@end
@[]
it's the short definition for NSArray
, I think this is the fastest method to concatenate strings.
If you don't want to use the category, use directly the componentsJoinedByString:
method:
NSString *joinedString = [@[firstString, secondString, thirdString] componentsJoinedByString:@""];
For all Objective C lovers that need this in a UI-Test:
-(void) clearTextField:(XCUIElement*) textField{
NSString* currentInput = (NSString*) textField.value;
NSMutableString* deleteString = [NSMutableString new];
for(int i = 0; i < currentInput.length; ++i) {
[deleteString appendString: [NSString stringWithFormat:@"%c", 8]];
}
[textField typeText:deleteString];
}
Use stringByAppendingString:
this way:
NSString *string1, *string2, *result;
string1 = @"This is ";
string2 = @"my string.";
result = [result stringByAppendingString:string1];
result = [result stringByAppendingString:string2];
OR
result = [result stringByAppendingString:@"This is "];
result = [result stringByAppendingString:@"my string."];
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];
listOfCatalogIDs =[@[@"id[]=",listOfCatalogIDs] componentsJoinedByString:@""];
When building requests for web services, I find doing something like the following is very easy and makes concatenation readable in Xcode:
NSString* postBody = {
@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
@"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
@" <soap:Body>"
@" <WebServiceMethod xmlns=\"\">"
@" <parameter>test</parameter>"
@" </WebServiceMethod>"
@" </soap:Body>"
@"</soap:Envelope>"
};