Re: NSMutableDictionary setObject:forKey:
Re: NSMutableDictionary setObject:forKey:
- Subject: Re: NSMutableDictionary setObject:forKey:
- From: Andy Lee <email@hidden>
- Date: Sat, 11 Jun 2005 20:19:39 -0400
On Jun 11, 2005, at 7:32 PM, mmalcolm crawford wrote:
(b) Of course there isn't a corresponding value, since you've just
"invented" the key. There isn't a corresponding value in dictionary.
Perhaps a few words about the basics would help.
A dictionary contains *pairs* of things. Each pair consists of a
"key" and a "value." Key, value. Two things. A pair. The key can
be any non-nil object that implements NSCopying. The value can be
any non-nil object.
A dictionary only contains as many key-value pairs as you put in.
That's what -setObject:forKey: is for. It either adds a key-value
pair or modifies an existing one. The first argument is a value, and
the second is a key:
[myMutableDictionary
setObject:myValue
forKey:myKey]; // <-- gives the dictionary it a *pair*
// consisting of myKey and myValue
As long as you keep passing different values for the key, -
setObject:forKey: adds a key-value pair each time you call it. But a
dictionary does not allow duplicate keys, so it must handle the case
when you pass a key that is already present. In this case, the
dictionary replaces the existing value for that key with the new
value you passed to the method.
Note that the dictionary does not retain a reference to the key you
passed to -setObject:forKey:. Instead, it makes a *copy* of the key
and retains that for its internal use. This helps guarantee that
keys are unique -- you can't add a key-value pair and then modify the
key so that it matches another key in the dictionary; you can modify
the key all you want, but it doesn't affect the copy of the key that
the dictionary uses. This is why keys must implement the NSCopying
protocol.
How does -setObject:forKey: decide whether a key is "already
present"? It uses the -isEqual: method to compare the key you give
it to the keys it contains. The dictionary also uses -isEqual: to
look up the key-value pair you want when you send an -objectForKey:
message:.
--Andy
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden