How did Apple implement NSSet?

Apple docs are NOT DOCUMENT NSSet "identity" concept.

I have some errors that seem to come from Apple code. For example, "[NSMutableSet minusSet]" never works for me, as documented, but I'm sure it's because of "identity."

eg. from: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSSet_Class/Reference/Reference.html#//apple_ref/occ/cl/NSSet

containsObject:

Gets a boolean value indicating whether the given object is present in the set.

YES if anObject is present in the set, otherwise NO.

What does it mean?

FYI what I tried:

  • implemented "isEqual:" for all classes in the set
  • checked that all classes are the same class (without mixing subclass / superclass)
  • implementd NSCopying for all classes in the set (no effect)
+4
source share
2 answers

In Cocoa, equality of an object is done using isEqual: and hash:

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html

From the notes for isEqual: ::

If two objects are equal, they must have the same hash value. This last point is especially important if you define isEqual: in a subclass and intend to put instances of this subclass in the collection. Make sure you also define a hash in your subclass.

Your subclasses will need to implement both of these functions so that they return the same thing. Once they do, they can be used correctly in Cocoa Collections.

The reason your NSSet equality won't work is because the sets use hashes (it is stored as a hash table), so if you only implemented isEqual: then there is a chance (good chance) that their hashes will differ .

+8
source

NSSet is a hash set in the classical sense, so you must implement the hash method to make sure objects are recognized equal. By default, hash simply returns a pointer to an object cast into an unsigned integer unique to each object, so even objects returning true for isEqual: will not be recognized as such. If you are interested in working with NSSet , you can take a look at the CFSet source code , which is a free bridge part of the Core Foundation NSSet counter.

+6
source

Source: https://habr.com/ru/post/1444590/


All Articles