In iOS, if you use = = to compare two objects, the memory address of the object is compared, which is generally not enough to meet our needs.
For example, there is a person class, and when all properties of the person object are consistent, it is assumed that the two objects are equal and can be implemented in the following way.
@interface Person:nsobject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *country;
@property (nonatomic, copy) NSString *pid;
@end
@implementation person
-(BOOL) IsEqual: (ID) Object {
if (self = = object) {
return YES;
}
if ([self class]! = [object class]) {
return NO;
}
Person *anotherperson = (person *) object;
if (![ _name IsEqualToString:anotherPerson.name]) {
return NO;
}
if (![ _country IsEqualToString:anotherPerson.country]) {
return NO;
}
if (![ _pid IsEqualToString:anotherPerson.pId]) {
return NO;
}
return YES;
}
-(Nsuinteger) hash {
Nsuinteger Namehash = [_name hash];
Nsuinteger Countryhash = [_country hash];
Nsuinteger Pidhash = [_pid hash];
return Namehash ^ Countryhash ^ pidhash;
}
@end
This basically satisfies the demand.
Similarly, we can implement a specific method of equality judgment, similar to the Isequaltostring method of the NSString class, which can be implemented in the following way.
@implementation person
-(BOOL) Isequaltoperson: (person *) Anotherperson {
if (self = = Anotherperson) {
return YES;
}
if (![ _name IsEqualToString:anotherPerson.name]) {
return NO;
}
if (![ _country IsEqualToString:anotherPerson.country]) {
return NO;
}
if (![ _pid IsEqualToString:anotherPerson.pId]) {
return NO;
}
return YES;
}
-(BOOL) IsEqual: (ID) Object {
if ([self class] = = [Object class]) {
return [self Isequaltoperson: (person *) object];
}else{
return [Super Isequal:object];
}
}
-(Nsuinteger) hash {
Nsuinteger Namehash = [_name hash];
Nsuinteger Countryhash = [_country hash];
Nsuinteger Pidhash = [_pid hash];
return Namehash ^ Countryhash ^ pidhash;
}
@end
Note: The same object must have the same hash code, but the two hashes of the same object are not necessarily the same.
In addition, when you use a container, you should not change its hash code if you put a mutable object into the container.
For example:
Nsmutableset *set = [[Nsmutableset alloc] init];
Nsmutablearray *arraya = [@[@1, @2] mutablecopy];
[Set Addobject:arraya];
NSLog (@ "%@", set); {()}
Nsmutablearray *arrayb = [@[@1] mutablecopy];
[Set Addobject:arrayb];
NSLog (@ "%@", set); {((1), ())}
[Arrayb addobject:@2];
NSLog (@ "%@", set); {((), ())}
Magically put two equal arrays in set. Sometimes there are some unexpected problems that need special attention.
How does iOS compare the equality of two objects?