Junior — Middle
Millised on peamised kriteeriumid, millele objekt peab vastama, et õigesti lisada see Set kogumikku?
sobes.tech AI
Vastus AI-lt
To correctly add an object to a Set collection (for example, NSSet in iOS), the object must:
-
Correctly and consistently implement the
-hashand-isEqual:methods.-hashshould return the same value for objects considered equal.-isEqual:should precisely determine object equality.
-
Be immutable in the 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 to store 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 ensures that the Set correctly determines the uniqueness of objects.