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.
4 Answers
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.

- 1
- 1

- 714,442
- 84
- 1,110
- 1,523
-
so your answer is: NSSet compares all its objects with the newly inserted one to see if it's already exists? – Basheer_CAD May 14 '14 at 10:58
-
@Basheer_CAD Please re-read my answer, especially its last part, where I talk about checking a handful of objects based on their hash. – Sergey Kalinichenko May 14 '14 at 11:03
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.

- 4,396
- 16
- 19
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

- 1
- 1

- 25,682
- 7
- 67
- 76
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

- 21,488
- 17
- 97
- 161