Xetius
Xetius

Reputation: 46834

iPhone - How to build a list of unique items

I want an array which contains only unique items. I know I could do this with an NSDictionary adding items with keys and then get allKeys. This would ensure that the NSArray contains only unique items, but I feel that this would be overkill and believe that there should be an easier way to do this, but cannot find one.

Upvotes: 1

Views: 360

Answers (3)

Peter N Lewis
Peter N Lewis

Reputation: 17811

NSArray* uniqueArray = [[NSSet setWithArray:originalArray] allObjects];

Uniqueness is based on the isEqual: method.

Upvotes: 6

Marco Mustapic
Marco Mustapic

Reputation: 3859

Use NSSet or NSMutableSet for this. Keep in mind that uniqueness will be based on object address if you don't override the isEqual: method. Unless, of course, you are using classes that implement that method (NSNumber, NSValue, for example).

Upvotes: 2

Jason Coco
Jason Coco

Reputation: 78373

You can use NSSet for this

Upvotes: 1

Related Questions