Junior — Middle
What are the main criteria that an object must meet for correct addition to a Set collection?
sobes.tech AI
Answer from AI
To correctly add an object to a collection like Set (for example, NSSet in iOS), the object must:
-
Implement the
-hashand-isEqual:methods correctly and consistently.-hashshould return the same value for objects considered equal.-isEqual:should precisely determine object equality.
-
Be immutable with respect to fields involved in hash calculation and comparison while the object is in the Set. Otherwise, the integrity of the collection will be compromised.
For example, if you create your own class for storage in NSSet, override these methods:
- (NSUInteger)hash {
return self.identifier.hash;
}
- (BOOL)isEqual:(id)object {
if (self == object) return YES;
if (![object isKindOfClass:[MyClass class]]) return NO;
return [self.identifier isEqual:((MyClass *)object).identifier];
}
This guarantees that the Set will correctly determine the uniqueness of objects.