How to join NSArray elements into an NSString?

-componentsJoinedByString: on NSArray should do the trick.


NSArray * stuff = /* ... */;
NSString * combinedStuff = [stuff componentsJoinedByString:@"separator"];

This is the inverse of -[NSString componentsSeparatedByString:].


There's also this variant, if your original array contains Key-Value objects from which you only want to pick one property (that can be serialized as a string ):

@implementation NSArray (itertools)

-(NSMutableString *)stringByJoiningOnProperty:(NSString *)property separator:(NSString *)separator
{
    NSMutableString *res = [@"" mutableCopy];
    BOOL firstTime = YES;
    for (NSObject *obj in self)
    {
        if (!firstTime) {
            [res appendString:separator];
        }
        else{
            firstTime = NO;
        }
        id val = [obj valueForKey:property];
        if ([val isKindOfClass:[NSString class]])
        {
            [res appendString:val];
        }
        else
        {
            [res appendString:[val stringValue]];
        }
    }
    return res;
}


@end

Tags:

String

Cocoa