Nsdictionary implementation principle-ios hashing hash and isequal

Source: Internet
Author: User

Nsdictionary implementation principles-ios hashing hash and nscopying implementation of custom classes in IsEqual oc (isequal & Hash Implementation) http://blog.csdn.net/linshaolie/ article/details/41494303 iOS development Don't tell me you really know isequal and hash!http://m.blog.csdn.net/hx_lei/article/details/53885798http. ://WWW.JIANSHU.COM/P/915356E280FC

Nsdictionary (dictionary) uses hash table to realize the mapping and storage between key and value, and the design of hash function affects the efficiency of data lookup and access. The more evenly the data is distributed in the hash table, the higher its access efficiency. In Objective-c, the nsstring is usually used as the key value, and its internal hash function is also used to ensure that each node of the data is evenly distributed in the hash table by using the NSString object as the key value.

See one of the most common method prototypes in Nsdictionary:

[OBJC]View Plain Copy
    1. -(void) SetObject: (ID) anobject forkey: (id <NSCopying>) Akey;

as you can see from this method, you must follow the Nscopying protocol as the Key value. This is because within Nsdictionary, a new copy of the Akey object is copied. The AnObject object, in its interior, is a strong reference (retain or strong).

Now that you know that as a key value, you must follow the Nscopying protocol, stating that in addition to the NSString object, we can use other types of objects as key values for the nsdictionary. But that's not enough, as a key value, the type must also inherit from NSObject and overload two methods:

[OBJC]View Plain Copy
    1. -(Nsuinteger) hash;
[OBJC]View Plain Copy
    1. -(BOOL) IsEqual: (ID) object;
The hash method is used to calculate the hash value of the object, and the final hash value determines where the object is stored in the hash table. We rewrite the hash method because every key-value is deposited into nsdictionary and Nsset, The dictionary will first compare the hash of the key being inserted and all the key.hash that already exist in the dictionary, ultimately deciding whether to add a key or overwrite the original key.  However, with the Key.hash comparison, sometimes 2 objects hash the same situation, it is necessary to call the IsEqual method to determine the final decision, 2 key objects are the same. Considerations for nscopying implementation of custom classes in OC (IsEqual & Hash Implementation) http://blog.csdn.net/hxmcnu/article/details/52029097

In OC, if a custom class is to be considered for assignment, persistence, saving to other containers for all cases of medium-sized object copying and comparison, here is a more comprehensive example of a custom, which is recorded only:

Custom classes:

KeyValuePairs.h:

[OBJC]View Plain Copy
    1. #import <Foundation/Foundation.h>
    2. @interface Keyvaluepairs:nsobject <NSCopying>
    3. @property (Nonatomic,strong) NSString *identifier;
    4. @property (Nonatomic,strong) NSString *name;
    5. @end
KEYVALUEPAIRS.M:

[OBJC]View Plain Copy
  1. #import "KeyValuePairs.h"
  2. @implementation Keyvaluepairs
  3. -(ID) Copywithzone: (Nszone *) zone
  4. {
  5. Keyvaluepairs *KVP = [[[Self class] allocwithzone:zone] init];
  6. Kvp.identifier = Self.identifier;
  7. Kvp.name = Self.name;
  8. return kvp;
  9. }
  10. -(BOOL) Isequaltokeyvaluepairs: (Keyvaluepairs *) kvp{
  11. if (!KVP) {
  12. return NO;
  13. }
  14. BOOL haveequalname = (!self.name &&!kvp.name) | | [Self.name IsEqualToString:kvp.name];
  15. BOOL haveequalidentifier = (!self.identifier &&!kvp.identifier) | | [Self.identifier IsEqualToString:kvp.identifier];
  16. return haveequalname && haveequalidentifier;
  17. }
  18. #pragma mark-nsobject
  19. -(BOOL) IsEqual: (ID) object{
  20. if (self = = object) {
  21. return YES;
  22. }
  23. if (![ Object Iskindofclass:[keyvaluepairs Class]]) {
  24. return NO;
  25. }
  26. return [self isequaltokeyvaluepairs: (Keyvaluepairs *) object];
  27. }
  28. -(Nsuinteger) hash {
  29. return [self.name hash] ^ [self.identifier hash];
  30. }
  31. @end

Test:

[OBJC]View Plain Copy
  1. Nsmutabledictionary *nameswillupdatedic = [[Nsmutabledictionary alloc] init];
  2. Nsmutablearray *names = [[Nsmutablearray alloc] init];
  3. for (int i = 0; i<1000; i++) {
  4. NSString *name = [NSString stringwithformat:@ "%d_zhangsan", I];
  5. NSString *identifier = [NSString stringwithformat:@ "%d_identifier", I];
  6. NSString *strobj = [NSString stringwithformat:@ "%d_strobj", I];
  7. Keyvaluepairs *KVP = [[Keyvaluepairs alloc] init];
  8. Kvp.identifier = identifier;
  9. Kvp.name = name;
  10. [Nameswillupdatedic setobject:strobj FORKEY:KVP];
  11. [Names ADDOBJECT:KVP];
  12. }
  13. for (int j = 0; j<1000; j + +) {
  14. int index = Arc4random ()%1000;
  15. Keyvaluepairs *KVP = [names Objectatindex:index];
  16. NSString *strobj = [Nameswillupdatedic OBJECTFORKEY:KVP];
  17. NSString *msg = [NSString stringwithformat:@ "index:%d,identifier:%@,email:%@,strobj:%@", Index,kvp.identifier, Kvp.name,strobj];
  18. NSLog (@ "%@", msg);
  19. }
Note: 1. Why must the custom class implement the Nscopying protocol? This is because by Key-value 2 objects into the dictionary, the dictionary will copy the key to the operation, and the value object to retain operation, if the custom class does not implement the copy protocol, then it cannot be used as the Dictionary key object. 2, if the custom class does not rewrite IsEqual, then by default uses the memory address compares two objects, may have the unexpected result 3, isequal and the hash method to rewrite at the same time, otherwise the IsEqual method judgment will be incorrect

Nsdictionary implementation principle-ios hashing hash and isequal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.