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

I am trying to print an NSSet in one line, separating the comma, but without the trailing comma or space. How can i do this?

I know 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 the sets are not indexed, I cannot do this.

thank

+5
source share
2 answers

You can always make an array from a set, for example:

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 indicated in your post:

BOOL isFirst = YES;
for (id element in mySet) {
    if (!isFirst) {
        [outputStringArray appendString:@", "];
    } else {
        isFirst = NO;
    }
    [outputStringArray appendFormat:@"%@", element];
}
+10
source

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

NSSet *myset = ....;
NSString *joinedString = [[myset allObjects] componentsJoinedByString:@", "];
+7
source

All Articles