在循环目标-c中追加字符串

时间:2013-08-12 16:18:21

标签: objective-c nsstring

我有一个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);
}

2 个答案:

答案 0 :(得分:7)

NSString *allFriends = [[friendPicker.selection valueForKey:@"name"] componentsJoinedByString:@", "];

答案 1 :(得分:4)

我会这样做:

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

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