Re: NSMutableDictionary Q's
Re: NSMutableDictionary Q's
- Subject: Re: NSMutableDictionary Q's
- From: Andrew Thompson <email@hidden>
- Date: Tue, 7 Jan 2003 00:57:38 -0500
On Tuesday, Jan 7, 2003, at 00:07 America/New_York, Mike McCune wrote:
well, I finally figured out what the problem was and it had to do with
how I was obtaining the strings to put in my data objects. I wasn't
getting them correctly from the objects I was using. I realize this
sounds confusing. and just to clear things up, the example I put in my
last message wasn't the actual code I was using, it was just something
I thought up on the spot.
There is if it's passed a NSMutableString. The dictionary will not
retain keys, it will copy them. This string is being used as a key, I
would copy it if I were programming it.
--__--__--
here's my question though, how come all the examples, documentation,
and books suggest doing it the opposite from how your describing, ie
instead of copying, just retaining. doesn't copying just add an extra
layer of redundancy?
The point is the String is *mutable* and its being used as a key inside
the dictionary.
If the dictionary doesn't copy it, someone could change it after it
gets added, and then Bad Things typically happen.
(imagine the dictionary is a hash table, altering the key will change
the hash code, but the dictionary won't know this has happened).
eg,
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableString *key = [[NSMutableString alloc] initWithString:
@"hello"];
NSMutableDictionary *entries = [NSMutableDictionary
dictionaryWithCapacity: 5];
[entries setObject: @"World" forKey: key];
[key appendString: @" hello hello"];
NSLog(@"%@", [entries objectForKey: key]);
NSLog(@"%@", [entries objectForKey: @"hello"]);
[pool release];
return 0;
}
Prints
2003-01-07 00:54:39.064 CocoaDictionaryText[1453] (null)
2003-01-07 00:54:39.065 CocoaDictionaryText[1453] World
Which proves the dictionary copies 'key'.
Mutable keys are a bad idea in most dictionary/map-like structures.
At best you get code which doesn't do what the developer expects.
At worst you break the data structure's internals and who knows what
happens.
AndyT (lordpixel - the cat who walks through walls)
A little bigger on the inside
(see you later space cowboy ...)
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.