Objective-C从对象数组中创build逗号分隔string的最简单方法

所以我有一个nsmutablearray与一堆对象在里面。 我想创build一个逗号分隔的每个对象的id值的string。

使用NSArray实例方法componentsJoinedByString: NSArray

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

例:

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

如果你在Swift中search相同的解决scheme,你可以使用这个:

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

为了确保你的数组不包含零值,你可以使用一个filter:

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

从数组创buildstring:

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

从string创build数组:

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

Swift 🙂

  var commaSeparatedString = arrayOfEntities.joinWithSeparator(",")