Search code examples
iphoneobjective-cnssetnsmutableset

Objective c - NSMutableSet unique object property


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.


Solution

  • 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 an NSObject 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 override hash method as well

    // In your Person.m
    - (BOOL)isEqual:(id)anObject
    {
        return [self.personId isEqual:anObject.personId]; 
        // If it's an object. Otherwise use a simple comparison like self.personId == anObject.personId
    }
    
    - (NSUInteger)hash
    {
        return self.personId; //Must be a unique unsigned integer
    }