Techniques for implementing -hash on mutable Cocoa objects

后端 未结 6 558
终归单人心
终归单人心 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:32

    My reading of the documentation is that a mutable object's value for hash can (and probably should) change when it is mutated, but should not change when the object hasn't been mutated. The portion of the documentation to which to refer, therefore, is saying, "Don't mutate objects that are stored in a collection, because that will cause their hash value to change."

    To quote directly from the NSObject documentation for hash:

    If a mutable object is added to a collection that uses hash values to determine the object’s position in the collection, the value returned by the hash method of the object must not change while the object is in the collection. Therefore, either the hash method must not rely on any of the object’s internal state information or you must make sure the object’s internal state information does not change while the object is in the collection.

    (Emphasis mine.)

提交回复
热议问题