Search code examples
iosnsset

How NSSet make sure the uniqueness of it objects?


I want to know how NSSet make sure that it has only unique objects? When we try to add duplicate value, then on which criteria it decides that it has already this value? I want to know the underlying uniqueness criteria.


Solution

  • NSSet uses your object's implementation of isEqual: method to decide object equality. It also uses hash to make the lookup much faster.

    -(BOOL)isEqual:(id)other;
    -(NSUInteger)hash;
    

    When two objects are equal, their hash methods must return the same value (objects with the same hash, however, may not necessarily be equal to each other).

    When your hash and isEqual: are implemented properly, NSSet can decide the equality by checking only a handful of objects whose hash "collides" with the hash of the object you are adding to the set.