Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumber as key for NSDictionary

Tags:

objective-c

I was wondering how keys work in a NSDictionary. Usually, I will use a NSString as a key for example:

NSString *stringKey = @"stringKey";
[mydict objectForKey:stringKey];

What if I wanted to use a NSNumber:

NSNumber *numberKey = [NSNumber numberWithInt:3];
[mydict objectForKey:numberKey];

Does the dictionary go look for the key with number 3? or would it just compare the address of the numberKey?

like image 533
prostock Avatar asked Sep 07 '11 17:09

prostock


People also ask

What is NSDictionary in Objective c?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.


1 Answers

Two keys are equal if and only if [key1 isEqual:key2]. Some classes may go with the -[NSObject isEqual:] implementation of return self == other;, but it's quite common for classes (such as NSString, NSNumber, etc) to override it to do more context-specific comparison.

like image 111
Dave DeLong Avatar answered Sep 22 '22 09:09

Dave DeLong