4

我有下一个将 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

如何重写它以避免警告?

4

2 回答 2

16

还有另一种方法可以用更少的代码行来实现你想要做的事情:

您可以使用以下方法获取 NSSet 对象数组:

NSArray *myArray = [mySet allObjects];

您可以将数组转换为字符串:

NSString *myStr = [myArray componentsJoinedByString:@","];
于 2013-08-14T17:24:22.513 回答
1

stringByReplacingCharactersInRange方法的返回类型NSString。您将其分配给NSMutableString. 使用可变副本。

resultString = [[resultString stringByReplacingCharactersInRange:lastComma  //2
                                                             withString: @""]mutablecopy]
于 2013-08-14T17:22:09.937 回答