In my app I have a class Person
with personId
property.
Now I need some data structure to hold a bunch of unique Person
objects (unique = different personId)
So I guess I should use NSMutableSet as my data structure, but how do I make the NSMutableSet compare the personId
property when adding a person (so I won't add the same person more then ones)?
My goal is to have a collection of unique persons all the time (even if I add two persons with the same id), I want that the NSMutableSet will do all the hard work for me and if I'm adding a person that already exists it won't add it twice.
You can achieve that by understanding how the comparison is made by the
NSSet
. When you add a new object to the set,isEqual:
method is called (it's anNSObject
method) against each of the set's elements. So what you can do is override this method and provide a custom comparison like this:NOTE:
If you override
isEqual:
method you must overridehash
method as well