1

我有一个运行未知次数的 for-in 循环,当它完成运行时,我希望所有名称都像这样附加:name1, name2,name3等等。

如何在循环中附加字符串?

我在想这样的事情:

if (donePressed)
{
    NSString *allFriends;
    selectedFriends = friendPicker.selection;
    for (NSDictionary * friend in selectedFriends)
    {
        NSString * friendName = [friend objectForKey:@"name"];
        // some built-in method that appends friendName to allFriends with a ", " between them
    }

    NSLog(@"%@",selectedFriends);
}
4

2 回答 2

7
NSString *allFriends = [[friendPicker.selection valueForKey:@"name"] componentsJoinedByString:@", "];
于 2013-08-12T16:21:29.243 回答
4

我会这样做:

NSMutableString *nameString = [[NSMutableString alloc]init];
for loop (...) {
    NSString *currentName = [friend objectForKey:@"name"];
    [nameString appendString:[NSString stringWithFormat:@"%@, ",currentName]];
}
NSLog(@"%@",nameString);

我上面的答案看起来更好,该函数可能不会,在列表末尾留下尾随。我的必须用它NSMakeRange()来修剪尾随的逗号。

于 2013-08-12T16:29:25.337 回答