Techniques for implementing -hash on mutable Cocoa objects

后端 未结 6 553
终归单人心
终归单人心 2020-12-31 10:06

The documentation for -hash says it must not change while a mutable object is stored in a collection, and similarly the documentation for -isEqual:

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-31 10:38

    The question here isn't how to meet both of these requirements, but rather which one you should meet. In Apple's documentation, it is clearly stated that:

    a mutable dictionary can be put in a hash table but you must not change it while it is in there.

    This being said, it seems more important that you meet the equality requirement of hashes. The hash of an object should always be a way to check if an object is equal to another. If this is ever not the case, it is not a true hash function.

    Just to finish up my answer, I'll give an example of a good hash implementation. Let's say you are writing the implementation of -hash on a collection that you have created. This collection stores an array of NSObjects as pointers. Since all NSObjects implement the hash function, you can use their hashes in calculating the collection's hash:

    - (NSUInteger)hash {
        NSUInteger theHash = 0;
        for (NSObject * aPtr in self) { // fast enumeration
            theHash ^= [aPtr hash];
        }
        return theHash;
    }
    

    This way, two collection objects containing the same pointers (in the same order) will have the same hash.

提交回复
热议问题