Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C How to print NSSet on one line (no trailing comma / space)

Tags:

objective-c

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

like image 644
flux Avatar asked Mar 13 '13 10:03

flux


2 Answers

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];
}
like image 67
Sergey Kalinichenko Avatar answered Nov 09 '22 03:11

Sergey Kalinichenko


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

NSSet *myset = ....;
NSString *joinedString = [[myset allObjects] componentsJoinedByString:@", "];
like image 36
Joris Kluivers Avatar answered Nov 09 '22 04:11

Joris Kluivers