Reload hash and isEqual: method, reload hashisequal
Overload hash and isEqual: Method
Preface
NSObject comes with the hash and isEqual methods, which serve the data structure with the hash table structure. The NSObject built-in hash function is equivalent to the key in the f (key) function of the hash table. This "unique" key needs to be generated by the user. The user determines the algorithm used.
Preparation
/// Model. h // Hash /// Created by YouXianMing on 16/4/15. // Copyright©2016 YouXianMing. all rights reserved. // # import <Foundation/Foundation. h> @ interface Model: NSObject <NSCopying> @ property (nonatomic, strong) NSString * firstName; @ property (nonatomic, strong) NSString * lastName; @ end
/// Model. m // Hash /// Created by YouXianMing on 16/4/15. // Copyright©2016 YouXianMing. all rights reserved. // # import "Model. h "# define NSUINT_BIT (CHAR_BIT * sizeof (NSUInteger) # define NSUINTROTATE (val, howmuch) (NSUInteger) val)
Test
1. Check whether the test object is the same (print the information)
The reason is that the hash algorithm of the two objects ensures the difference of the objects based on the uniqueness of the attribute values. That is to say, as long as the values of the two objects are consistent, the two objects are equal.
2. Test the dictionary setObject: forKey: method (print the information carefully)
The dictionary uses the modelB object as the key value to find the value stored when modelA is used as the key value. This is because we have made modelA and modelB "equal". Refer to test 1.
When setting the key value, the dictionary needs to copy the key value object (the key value object must implement the NSCopying Protocol). That is to say, when modelA is used as the key value, it has been copied by the dictionary, because the dictionary needs to ensure that the key value is not changeable. Otherwise, an object as a key value changes the hash value of this object by modifying its internal attributes, and the object cannot be found.
You can observe the breakpoint process (the dictionary first obtains the hash value of the external object, and then compares it with its own key value object to execute isEqual: method. If the comparison result is the same, make sure it is the same object)
When the dictionary executes the setObject: forKey: method, it first executes the hash method of the key value object to generate a key value, and then copies the key value object.
3. Test addObject of NSSet: method (print the information carefully)
AddObject: The method execution process is as follows: first obtain the hash value of the object modelA, then obtain the hash value of modelB when adding modelB, and then compare it. If the comparison results are consistent, this is the same object.