Limit duplicate entry in NSArray

I have an array containing multiple duplicate entries.

First, is there a way to limit duplicate entries when inserting data?

Secondly, if the array already has duplicate values ​​than in any other way, we can only get unique values ​​from this array, I heard about this NSSet, but I have no idea how to use it.

+4
source share
3 answers

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++; } } 
+13
source

NSMutableSet is probably the most logical to use.

However, it should be warned that the set does not support the order of its elements (since the set is, by definition, disordered).

If this is a problem for you, you have several options:

  • duplicate a set of functions using NSMutableArray by calling containsObject: before each call to addObject: (perhaps, but potentially slow, since arrays have O (n) lookup times)
  • use another object.

If you move on to the second option, I would recommend taking a look at the excellent CHDataStructures infrastructure that has a subclass of NSMutableSet called CHOrderedSet , which is a collection that supports insertion order. (And since it is a subclass, it has the same API as NSMutableSet )

+9
source

If you've heard of NSSet, have you read the documentation ? The API is similar to NSArray and is very simple. Like NSArray vs. NSMutableArray, you should use NSMutableSet if you need membership tests on the fly.

+5
source

All Articles