这可能是一个相当基本的问题,但尽我所能,我找不到导致它的原因。
我写了以下代码:
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]
在添加为 Object 时被解释为 NSNull myDictionary
,而在将相同的表达式添加到 NSArray 时,它会被视为对象values
。
并且记录myDictionary
我注意到这确实是正在发生的事情。谁能向我解释为什么?