Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make unique NSMutableArray or NSMutableSet

I'm currently enumerating through NSMutableArray (or NSMutableSet) elements to find duplicates and remove them.

For example, if array/set has values [@"a", @"b", @"b", @"c"], the end result should be [@"a", @"b", @"c"].

Since I'm comparing NSStrings, I'm using isEqualTo: method to check if strings are equal.

Is there a more efficient way to do remove duplicate entries than to loop through all of them and check if duplicate exists?

like image 821
Rudi Avatar asked Jul 21 '09 18:07

Rudi


4 Answers

An NSSet does exactly what you're trying to do: it is a (unordered) collection of unique items. So, you can find the unique items in your array like so:

NSSet *uniqueElements = [NSSet setWithArray:myArray];

// iterate over the unique items
for(id element in uniqueElements) {
  // do something
}

NSSet most likely uses a hash algorithm to make insertion O(1) (compared to O(n^2) to check if each item is unique by iteration), but the Apple documentation does not make such a guarantee so you probably shouldn't count on that implementation detail.

If, for some reason you need to keep the unique items in a sorted (ordered) collection, you can turn the set back into an array with -[NSSet allObjects] and then sort the resulting array.

like image 135
Barry Wark Avatar answered Nov 19 '22 09:11

Barry Wark


An NSSet or NSMutableSet will guarantee that you don't have duplicate objects. It will work for NSStrings as in your example, but for your own classes keep in mind what do you mean by "equal" and implement the hash and isEqual: methods accordingly.

like image 39
Marco Mustapic Avatar answered Nov 19 '22 09:11

Marco Mustapic


A set never contains duplicate elements, so simply creating an NSMutableSet should guarantee uniqueness of values.

like image 25
Daniel Dickison Avatar answered Nov 19 '22 10:11

Daniel Dickison


Only this line of code will work fine .

NSSet *mySet = [NSSet setWithArray:myArray];

now mySet will have unique elements.

like image 26
Chandramani Avatar answered Nov 19 '22 10:11

Chandramani