Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i make NSMutableArray only accept unique values?

Tags:

objective-c

NSMutableArray *sectionTitles;
[sectionTitles addObject:due];

How do I just add unique values to an array?

like image 289
Jules Avatar asked Nov 05 '10 12:11

Jules


2 Answers

See Rudolph's Answer

My old answer below is now outdated and has been for awhile. Rudoph's reference to NSOrderedSet / NSMutableOrderedSet is the correct one since these classes were added after this Q and my A.

Old Answer

As Richard said, NSMutableSet works well but only if you don't need to maintain an ordered collection. If you do need an ordered collection a simple content check is the best you can do:

if (![myMutableArray containsObject:newObject])
    [myMutableArray addObject:newObject];

Update based on comment

You can wrap this in a method like -addUniqueObject: and put it in an NSMutableArray category.

like image 62
Joshua Nozzi Avatar answered Oct 14 '22 13:10

Joshua Nozzi


More 2012-ish answer (in case someone stumbled upon this in the future):

Use NSOrderedSet and NSMutableOrderedSet.

A note about performance right from NSOrderedSet docs:

You can use ordered sets as an alternative to arrays when the order of elements is important and performance in testing whether an object is contained in the set is a consideration— testing for membership of an array is slower than testing for membership of a set.

like image 38
Rudolf Adamkovič Avatar answered Oct 14 '22 12:10

Rudolf Adamkovič