NSDictionary查找间歇性失败

时间:2014-07-07 06:58:28

标签: objective-c nsdictionary

我遇到了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;
}

0 个答案:

没有答案