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

Objective CArraysSwiftNsmutablearray

Objective C Problem Overview


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.

Objective C Solutions


Solution 1 - Objective C

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: ",")

Solution 2 - Objective C

If you're searching for the same solution in Swift, you can use this:

var array:Array<String> = ["string1", "string2", "string3"]
var commaSeperatedString = ", ".join(array) // Results in string1, string2, string3

To make sure your array doesn't contains nil values, you can use a filter:

array = array.filter { (stringValue) -> Bool in
    return stringValue != nil && stringValue != ""
}

Solution 3 - Objective C

Create String from Array:

-(NSString *)convertToCommaSeparatedFromArray:(NSArray*)array{
    return [array componentsJoinedByString:@","];
}

Create Array from String:

-(NSArray *)convertToArrayFromCommaSeparated:(NSString*)string{
    return [string componentsSeparatedByString:@","];
}

Solution 4 - Objective C

Swift

var commaSeparatedString = arrayOfEntities.joinWithSeparator(",")

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
QuestionJhorraView Question on Stackoverflow
Solution 1 - Objective CrdelmarView Answer on Stackoverflow
Solution 2 - Objective CAntoineView Answer on Stackoverflow
Solution 3 - Objective CmedaView Answer on Stackoverflow
Solution 4 - Objective CiooplView Answer on Stackoverflow