1

I have a for-in loop running unknown num of times, when its finished running I want to have all names appending like so: name1, name2,name3 and so on.

How do I append the strings within the loop ?

I was thinking of something like this :

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 Answers 2

7
NSString *allFriends = [[friendPicker.selection valueForKey:@"name"] componentsJoinedByString:@", "];
Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer, I should have reloaded the page :-)
@JustinAmberson OP will probably end up with something closer to your code the first time an entity has a NULL name. My code is a bit fragile in its terseness.
4

I would do this:

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

The answer above mine looks better, that function probably doesn't leave a trailing , at the end of the list. Mine would have to use NSMakeRange() to trim the trailing comma.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.