Jules
Jules

Reputation: 7766

How can i make NSMutableArray only accept unique values?

NSMutableArray *sectionTitles;
[sectionTitles addObject:due];

How do I just add unique values to an array?

Upvotes: 15

Views: 9078

Answers (3)

Joshua Nozzi
Joshua Nozzi

Reputation: 61228

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.

Upvotes: 30

Rudolf Adamkovič
Rudolf Adamkovič

Reputation: 31486

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.

Upvotes: 19

Richard J. Ross III
Richard J. Ross III

Reputation: 55533

Use NSMutableSet, it is best for these situations

iOS Reference

Mac OSX Reference

Upvotes: 5

Related Questions