NSDictionary objectForKey: rely on identity or equality?

Let's say I have an object with a name Personthat has a property socialSecurityNumber, and this class overrides the method isEqual:to return true when the social security number properties are equal. And say that I put a bunch of instances Personin NSDictionary.

If I now create an instance of an object newPersonthat, as it turns out, has the same social security number as in the dictionary, and I do [myDictionary objectForKey:newPerson], will it use isEqual:and return YES, or will it compare pointers and return NO?

I know that I can write a simple test to find out, but I want to understand exactly how it objectForKey:finds a match in the dictionary, and in general, how much is it agreed through Cocoa (i.e., NSArray indexofObject:work the same way?)

+5
source share
2 answers

NSDictionaryworks like a hash table. Therefore, it uses both -hash, and -isEqual:to find an object in the dictionary corresponding to this key.

So, in order to answer your question for NSDictionary, it uses isEqual:rather than comparing pointers. But you must also implement hashin addition to isEqual:your class Personin order for this to work.

- . , , - . . , ( isEqual:).

, . , isEqual: . , .

0, isEqual: , . anObject isEqual:. , isEqual: ( NSObject) YES.


: , , "" " " "" .

+10

Cocoa (.. NSArray indexofObject: ?)

. , : isEqual hash. , , . NSObject , isEqual, .

isEqual NSObject

, . , isEqual: . , .

+1

All Articles