NSSet 不包含对象,即使它们是相等的
NSSet didn't contain the object even though they are equal
Person
class:
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@end
我重写了它的 isEqual:
方法:
- (BOOL)isEqual:(id)object {
Person *person = (Person *)object;
return [self.name isEqualToString:person.name];
}
然后我做了一个测试:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
Person *p1 = [[Person alloc] init];
p1.name = @"Jack";
Person *p2 = [[Person alloc] init];
p2.name = @"Jack";
if ([p1 isEqual:p2]) {
NSLog(@"p1 isEqual p2");
} else {
NSLog(@"p1 not Equal p2");
}
NSMutableSet *set = [NSMutableSet set];
[set addObject:p1];
if ([set containsObject:p2]) {
NSLog(@"contain p2");
} else {
NSLog(@"not contain p2");
}
}
控制台打印:
p1 isEqual p2
not contain p2
关于方法containsObject:
:
Each element of the set is checked for equality with anObject until a match is found or the end of the set is reached. Objects are considered equal if isEqual: returns YES.
所以我现在有点困惑:
既然p1
等于p2
,为什么集合中不包含p2
?
来自documentation for the NSObject protocol:
If two objects are equal, they must have the same hash value. This
last point is particularly important if you define isEqual: in a
subclass and intend to put instances of that subclass into a
collection. Make sure you also define hash in your subclass.
Person
class:
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@end
我重写了它的 isEqual:
方法:
- (BOOL)isEqual:(id)object {
Person *person = (Person *)object;
return [self.name isEqualToString:person.name];
}
然后我做了一个测试:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
Person *p1 = [[Person alloc] init];
p1.name = @"Jack";
Person *p2 = [[Person alloc] init];
p2.name = @"Jack";
if ([p1 isEqual:p2]) {
NSLog(@"p1 isEqual p2");
} else {
NSLog(@"p1 not Equal p2");
}
NSMutableSet *set = [NSMutableSet set];
[set addObject:p1];
if ([set containsObject:p2]) {
NSLog(@"contain p2");
} else {
NSLog(@"not contain p2");
}
}
控制台打印:
p1 isEqual p2
not contain p2
关于方法containsObject:
:
Each element of the set is checked for equality with anObject until a match is found or the end of the set is reached. Objects are considered equal if isEqual: returns YES.
所以我现在有点困惑:
既然p1
等于p2
,为什么集合中不包含p2
?
来自documentation for the NSObject protocol:
If two objects are equal, they must have the same hash value. This last point is particularly important if you define isEqual: in a subclass and intend to put instances of that subclass into a collection. Make sure you also define hash in your subclass.