What does the 'hash' method do in Objective-C
Occasionally, when I am looking 开发者_开发技巧down the list of selectors that a object responds to, I see hash
come up. For a while now, I have wondered what it meant, but I never came around to finding out.
I would really appreciate it if you could tell me what the selector does and common uses for doing so.
It computes a hash of the object, which is especially useful in HashTables like when the object is used as a key for an NSDictionary
.
An object hash
has to have the following properties:
- Two objects of the same class that are to be considered equal should return the same hash
- Two objects with a diffent hash will never be considered as equal
- Two objects with the same hash are not necessary equal to each other; anyway, the more unique the hash is, the better the performance for
NSDictionary
lookup will be. - If should also be computable as fast as possible to avoid performance issues in dictionaries
For more info, read the NSObject Protocol documentation where this hash
method is defined.
For example the hash
function for a string could be the number of characters of this string, or the sum of the ascii codes of its character, or anything similar.
When you search for a given key in an NSDictionary
, one solution would be to compare the searched key with all other keys in the dictionary, which would need to loop thru all the keys and call isEqual
on each key, and that will take a long time if the dictionary have a lot of entries. So instead, Cocoa will compute the hash of the searched key, and compare it with all the (pre-computed) hashes of the keys in the dictionary.
This is much more efficient because it will only need to make comparisons between NSUInteger
values, even if the keys of the NSDictionary
are NSString
s or other objects, so this is really faster.
Once it has found the keys that have the same hash as the hash of the searched key, it can then loop thru all the keys with this hash and compare them with the searched key by calling isEqual
, but at this stage there will be much less keys to loop thru (and even possibly only one if the hash of the key is really unique)
It's used for implementing efficient hash tables in associative array data types such as NSDictionary
.
精彩评论