我有下一个代码,用于将NSSet转换为以逗号分隔的字符串:
-(NSString *)toStringSeparatingByComma
{
NSMutableString *resultString = [NSMutableString new];
NSEnumerator *enumerator = [self objectEnumerator];
NSString* value;
while ((value = [enumerator nextObject])) {
[resultString appendFormat:[NSString stringWithFormat:@" %@ ,",value]];//1
}
NSRange lastComma = [resultString rangeOfString:@"," options:NSBackwardsSearch];
if(lastComma.location != NSNotFound) {
resultString = [resultString stringByReplacingCharactersInRange:lastComma //2
withString: @""];
}
return resultString;
}
它似乎有效,但我在这里发出了两个警告:
1. format string is not a string literal (potentially insecure)
2. incompatible pointer types assigning to nsmutablestring from nsstring
如何重写它以避免警告?
答案 0 :(得分:16)
还有另一种方法可以用更少的代码行来实现你想要做的事情:
您可以使用以下方法获取NSSet对象数组:
NSArray *myArray = [mySet allObjects];
您可以将数组转换为字符串:
NSString *myStr = [myArray componentsJoinedByString:@","];
答案 1 :(得分:1)
stringByReplacingCharactersInRange
方法的返回类型NSString
。您将其分配给NSMutableString
。使用可变副本。
resultString = [[resultString stringByReplacingCharactersInRange:lastComma //2
withString: @""]mutablecopy]