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.
In this scenario, hash codes generate an index to store values. So, here, hashing is used to index and retrieve information from a database because it helps accelerate the process; it is much easier to find an item using its shorter hashed key than its original value.
The hash() method returns the hash value of an object if it has one. Hash values are just integers that are used to compare dictionary keys during a dictionary look quickly.
Hashed data maps the original string of characters to data of a fixed length.
Hashing technique is used to calculate the direct location of a data record on the disk without using index structure. In this technique, data is stored at the data blocks whose address is generated by using the hashing function. The memory location where these records are stored is known as data bucket or data blocks.
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:
NSDictionary
lookup will be.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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With