Re: NSDictionary key types
Re: NSDictionary key types
- Subject: Re: NSDictionary key types
- From: David Duncan <email@hidden>
- Date: Thu, 6 Jan 2011 12:47:29 -0800
On Jan 6, 2011, at 12:10 PM, Jon Sigman wrote:
> I'm a bit new to Cocoa, and I'm trying to get my head around NSDictionary. In
> the Apple documentation it says, "Each entry consists of one object that
> represents the key and a second object that is the key's value. ... In general,
> a key can be any object, but note that when using key-value coding the key must
> be a string."
>
> So, I supply an object that *represents* the key, meaning that this object
> itself is not the key, but it's value is? That makes sense for NSStrings, but
> not if the key is some other object without an obvious "value", like an NSArray.
> Are the two key types somehow treated differently?
The difference between the key and its value is just the same as having two different NSStrings that have the same contents but different addresses. For simplicity's sake, we'll consider C strings (although note that C strings cannot be used directly as a key in an NSDictionary)
char str1[] = "foo";
char str2[] = "foo";
Because these are two different arrays, they obviously have different addresses and as such you can't just use the pointer address for comparison, otherwise a different client of your dictionary may not be able to obtain the key's associated value. Therefore you must do comparisons based on the value of the key (the contents "foo").
For other data types the exact same thing applies. If you decided to use an array as a key, you would expect the array's content, not its address, to be the key for looking up the associated value. That is what is meant by NSDictionary using the contents of an object, and why it defines this as using -isEqual: for this comparison.
So knowing that, as long as [obj1 isEqual:obj2] returns true, then it must follow that [dict valueForKey:obj1] == [dict valueForKey:obj2] is also true.
--
David Duncan
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden