Objective-C Simplest way to create comma separated string from an array of objects

Jhorra picture Jhorra · Apr 26, 2012 · Viewed 37.7k times · Source

So I have a nsmutablearray with a bunch of objects in it. I want to create a comma separated string of the id value of each object.

Answer

rdelmar picture rdelmar · Apr 26, 2012

Use the NSArray instance method componentsJoinedByString:.

In Objective-C:

- (NSString *)componentsJoinedByString:(NSString *)separator

In Swift:

func componentsJoinedByString(separator: String) -> String

Example:

In Objective-C:

NSString *joinedComponents = [array componentsJoinedByString:@","];

In Swift:

let joinedComponents = array.joined(seperator: ",")