5

Im trying to print out an NSSet on a single line, comma separation but no trailing comma or space. how can i do this?

i know that this works for an array:

    NSMutableString *outputStringArray = [[NSMutableString alloc] init];
    NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity:10];

    for (int k = 0; k < [myArray count]; k++) {
        [outputStringArray appendFormat:@"%@, ", [myArray objectAtIndex:k]];
    }
    NSLog(@"%@", [outputStringArray substringToIndex:[outputStringArray length] - 2]);

but since sets don't have indexing i cant do this.

thanks

flux
  • 395
  • 1
  • 2
  • 13

2 Answers2

10

You can always make an array out of a set, like this:

NSArray *myArray = [mySet allObjects];

After that, you can get your string with componentsJoinedByString::

NSString *str = [myArray componentsJoinedByString:@", "];

Of course you can achieve the same effect with a simple loop similar to the one in your post:

BOOL isFirst = YES;
for (id element in mySet) {
    if (!isFirst) {
        [outputStringArray appendString:@", "];
    } else {
        isFirst = NO;
    }
    [outputStringArray appendFormat:@"%@", element];
}
CRD
  • 52,522
  • 5
  • 70
  • 86
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
7

Get the objects in your set as an array and use componentsJoinedByString:

NSSet *myset = ....;
NSString *joinedString = [[myset allObjects] componentsJoinedByString:@", "];
Joris Kluivers
  • 11,894
  • 2
  • 48
  • 47