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.
4 Answers
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: ",")
4 Comments
Jhorra
So the objects in my array have 4 or 5 properties, how do I tell it to join just the id values?
rdelmar
If you just log one of your objects what do you get? Just the id values? If so, that's what you'll get with componentsJoinedBuString: Try it and see.
Jack Lawrence
@Jhorra If you want an array of just one of the properties, you can do something really awesome:
[<NSArray instance> valueForKey:@"<string representation of property name>"] and it'll return an array of just that property. Then call componentsJoinedByString: on the result. Behind the scenes, the framework is iterating through all of the objects in the array and calling valueForKey: on them. Key-Value Coding is awesome!Jay Q.
For more KVC Collection Operators, check this out: nshipster.com/kvc-collection-operators
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 != ""
}
4 Comments
ultrageek
This doesn't seem to work for NSMutableArray in Swift. Searching Google has yet to reveal an answer.
cdf1982
@Twan Thank you, your answer is (almost) exactly what I was looking for... Almost, because I need to concatenate optional Strings, some of which could be nil (and so I don't want to concatenate them), but this solution doesn't accept optionals String, it requires to unwrap them... maybe you had a similar issue in the past, if so could you help me?
Antoine
@cdf1982 I've updated my answer. You can do this using the filter method.
cdf1982
@Twan it's perfect, thank you really, really, really very much! I'm just sorry that this is a comment and I can't accept it!
Swift
var commaSeparatedString = arrayOfEntities.joinWithSeparator(",")
3 Comments
handiansom
The question specified a programming language. Please consider changing it to objective - c.
Aleks N.
@handiansom That was 2012.
handiansom
Yeah I noticed too. ^ ^