Do not use NSSet .
You can only insert elements when you create it, and cannot change the elements contained after it was created.
If you want to add and remove objects on the fly, you can use NSMutableSet .
Below is a demo of using NSSet and NSMutableSet , and then converting NSSet to NSArray (if you want to do this):
- (void) NSMutableSetPrintTest { NSMutableSet *mutableSet = [[NSMutableSet alloc] init]; NSLog(@"Adding 5 objects (3 are duplicates) to NSMutableSet"); NSString *firstString = @"Hello World"; [mutableSet addObject:firstString]; [mutableSet addObject:@"Hello World"]; [mutableSet addObject:@"Goodbye World"]; [mutableSet addObject:@"Goodbye World"]; [mutableSet addObject:@"Goodbye World"]; NSLog(@"NSMutableSet now contains %d objects:", [mutableSet count]); int j = 0; for (NSString *string in mutableSet) { NSLog(@"%d: %@ <%p>", j, string, string); j++; } NSLog(@"Now, if we are done adding and removing things (and only want to check what is in the Set) we should convert to an NSSet for increased performance."); NSSet *immutableSet = [NSSet setWithSet:mutableSet]; NSLog(@"NSSet now contains %d objects:", [immutableSet count]); int i = 0; for (NSString *string in immutableSet) { NSLog(@"%d: %@ <%p>", i, string, string); i++; } [mutableSet release]; mutableSet = nil; NSLog(@"Now, if we are done with the sets, we can convert them back to an NSArray:"); NSArray *array = [immutableSet allObjects]; NSLog(@"NSArray contains %d objects", [array count]); int k = 0; for (NSString *string in array) { NSLog(@"%d: %@ <%p>", k, string, string); k++; } }
source share