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

↘锁芯ラ 提交于 2019-12-03 02:55:27

问题


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.


回答1:


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



回答2:


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 != ""
}



回答3:


Create String from Array:

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

Create Array from String:

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



回答4:


Swift :)

 var commaSeparatedString = arrayOfEntities.joinWithSeparator(",")


来源:https://stackoverflow.com/questions/10326762/objective-c-simplest-way-to-create-comma-separated-string-from-an-array-of-objec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!