tags:

views:

141

answers:

2

I have a NSMutableDictionary instance and the keys I'm using are NSNumber* type.

In the scenario I have, I'm trying to use 'objectForKey' to retrieve an object in my dictionary that I know is present. But I keep getting nil for the result unless I make convert the key from NSNumber to NSString.

NSNumber *itemId = [NSNumber numberWithInt:5];

id *existingItem = [forRemovalLookup objectForKey:itemId];
if (existingItem == nil)
{
  // expected: shouldn't be nil
  NSLog(@"!!!!!Not expecting this to be nil");
}

Is there another operation I should use to test for the presence of a specific key in a dictionary?

A: 

nevermind. pilot error.

Robin Jamieson
You should use comments to answer. I suggest deleting the question as it's not really helpful to others like this anymore.
Georg
+1  A: 

It would work, but only if [itemID hash] was equal to the key's hash, and if [itemID isEqual:] returned true when compared against the key in question. I think an NSNumber's hash is simply the number it holds, but the hash of a string would be completely different even if it was just a string representation of the same number. From memory, the hash of a string is calculated by multiplying each character value by the value of an accumulator times by a certain amount.

There might be something else I'm missing, but there was a discussion on the Cocoa mailing list about class behaviour inside collection objects and the general consensus was that if a class was to hold well in a collection it should correctly return decent values for -hash and -isEqual:.

I know this answer doesn't really help you in this situation, but it may shed some light on how dictionary collections work in Cocoa.

dreamlax