当作为NSDictionary的对象添加时,NSNumber numberWithInt导致NSNull

时间:2013-11-20 21:22:54

标签: ios objective-c nsdictionary nsnumber nsnull

这可能是一个相当基本的问题,但请尽可能地找不到导致它的原因。

我写了以下代码:

    NSMutableDictionary * myDictionary = [[NSMutableDictionary alloc] init];
    NSMutableArray * values = [[NSMutableArray alloc] init];

    for (int i=0; i<10; i++) {

        // create an object that can become a key in an NSDictionary
        CustomObjectAdoptingNSCopy * someKey = [[CustomObjectAdoptingNSCopy alloc] init];

        // create a random value that will become an object for myDictionary ...
        int someValue = rand()%10;

        // ... and which also gets to be an object in the values array, provided it isn't already stored there
        if ([values indexOfObject:[NSNumber numberWithInt:someValue]]==NSNotFound)
            [values addObject:[NSNumber numberWithInt:someValue]];

        // now associate someValue with someKey in myDictionary
        [myDictionary setObject:[NSNumber numberWithInt:someValue] forKey:someKey];
    }

    // read the data in myDictionary enumerating the NSArray values
    for (NSNumber * aValue in values){
        NSArray * objectsForValue = [myDictionary allKeysForObject:aValue];
        // now the data from objectsForValue are being used ...
    }

objectsForValue为空时,问题就会出现,这种问题不是一直发生,而是经常发生。如果我没有太多错误,这在逻辑上是不可能的,除非[NSNumber numberWithInt:someValue]在作为对象添加到myDictionary时被解释为NSNull,而同一表达式在被添加到NSArray时被视为对象{ {1}}。

并且记录values我注意到这确实是发生了什么。任何人都可以向我解释原因吗?

1 个答案:

答案 0 :(得分:1)

如果您没有覆盖-isEqual:-hash,那么CustomObjectAdoptingNSCopy的副本就不会相等。 NSObject的相等默认实现是对象标识。由于NSDictionary复制了密钥但副本不等于原始密钥,因此除非您要求密钥并使用它们,否则无法从字典中检索任何内容。原件不起作用。