This is probably a rather basic problem, but try as I might I can't find the reason that causes it.
I wrote the following code:
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 ...
}
The problem manifests when objectsForValue
is empty, which does not happen all the time but regularly. If I am not very much mistaken this is logically impossible unless [NSNumber numberWithInt:someValue]
gets interpreted as NSNull when added as Object to myDictionary
, while the same expression gets treated as an object when it is being added to the NSArray values
.
And logging myDictionary
I noticed that this is indeed what's happening. Can anybody explain to me why?