What the hash method does in Objective-C

Sometimes, when I look at the list of selectors that the object responds to, I see hash . For a while I wondered what that meant, but I never found out.

I would really appreciate it if you could tell me what the selector does and usually uses for this.

+6
source share
2 answers

It computes the hash of an object, which is especially useful in HashTables, for example, when the object is used as a key for an NSDictionary .

The hash object must have the following properties:

  • Two objects of the same class, which should be considered equal, must return the same hash
  • Two objects with a different hash will never be considered equal.
  • Two objects with the same hash are not necessarily equal to each other; Anyway, the more unique the hash is, the better the performance for finding NSDictionary .
  • If you should also calculate as quickly as possible to avoid performance problems in dictionaries

For more information, read the NSObject protocol documentation where this hash method is defined.


For example, for a hash function for a string, there may be the number of characters of this string or the sum of ascii codes of its character or something similar.

When you search for a given key in an NSDictionary , one solution would be to compare the key found with all the other keys in the dictionary, which would have to go through all the keys and call isEqual for each key, and this will take a lot of time if the dictionary contains many entries. So instead, Cocoa will calculate the hash of the key you are looking for and compare it with all the (pre-computed) hashes of the keys in the dictionary.

This is much more efficient, because comparing NSUInteger values ​​will only require comparison, even if the NSDictionary keys are NSString or other objects, so this is faster. After he finds the keys that have the same hash as the search hash, he can iterate over all the keys with this hash and compare them with the regular key by calling isEqual , but at this point there will be much fewer keys for the loop (and even only one possible if the key hash is really unique)

+8
source

It is used to implement efficient hash tables in associative array types such as NSDictionary .

0
source

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


All Articles