Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

take a look at Object Comparison in the official apple documentation. As you can see there most of the containers use hash to compare objects.

I want to know how NSSet make sure that it has only unique objects

Whenever you try to add object it will check for hash value of all other existing objects inside of it. Based on that it will keep it as unique

If two objects are equal, they must have the same hash value

When we try to add duplicate value, then on which criteria it decides that it has already this value?

if the new object hash value matches the existing then it will be considered as dublicate

Refer this Apple's documentation

enter image description here

First of all the set checks hash values of objects. If hashes are not equal it means that objects are guaranteed to be different. If hashes are equal it however doesn't mean that objects are neccessarily equal, so the set has to make sure and check their isEqual: methods

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top