我遇到了NSMutableDictionary
我在我的程序中使用的一些奇怪的行为,其中尽管对象存在,但字典中的查找返回nil
并且两个键为-isEqual:
调用返回true(我已为MyClass
覆盖)。会发生什么事?我错过了在NSDictionaries中使用自定义类的一些内容吗?
(lldb) p [(MyClass *)self.dict.allKeys[0] isEqual:object]
-> (BOOL) $7 = YES
(lldb) po self.dict[self.dict.allKeys[0]]
-> My Object Description!
(lldb) po self.dict[object]
-> nil
编辑:-copyWithZone:
和-isEqual:
//MyClass.m
-(BOOL)isEqual:(id)object {
if ([object isKindOfClass:[MyClass class]]) {
if(((MyClass *)object).someProperty == self.someProperty) { //someProperty is an enum type so direct comparison is fine
return YES;
}
return NO;
}
return NO;
}
-(id)copyWithZone:(NSZone *)zone {
MyClass *copy = [[[self class] alloc] init];
if (copy) {
copy.someProperty = self.someProperty; //again, someProperty is an enum type, no need to copy recursively
}
return copy;
}