How to join NSArray elements into an NSString?

CocoaString

Cocoa Problem Overview


Given an NSArray of NSStrings, is there a quick way to join them together into a single NSString (with a Separator)?

Cocoa Solutions


Solution 1 - Cocoa

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

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

Solution 2 - Cocoa

-componentsJoinedByString: on NSArray should do the trick.

Solution 3 - Cocoa

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3850View Question on Stackoverflow
Solution 1 - CocoaDave DeLongView Answer on Stackoverflow
Solution 2 - CocoaBJ HomerView Answer on Stackoverflow
Solution 3 - CocoaBen GView Answer on Stackoverflow