Retain counts with a dictionary
Retain counts with a dictionary
- Subject: Retain counts with a dictionary
- From: Jeffrey Mattox <email@hidden>
- Date: Sat, 15 Mar 2003 19:25:02 -0600
I am using an NSMutableDictionary as an associative array (a la, a
Perl hash, I'm in heaven :-).
I add keys (which are strings) to the dictionary. If the key already
exists, nothing happens; if the key does not exist, it gets added.
Since I'm only interested in the existence or not of theKey (in later
code, not shown), I have no need for the object, but it cannot be
nil, so I use @"". All this seems to work.
char *myCString;
NSString *thekey;
while (...) {
...
myCString = .... // varies
theKey = [[NSString alloc] initWithCString:myCString];
[theDictionary setObject:@"" forKey:theKey];
[theKey release];
}
The documentation for NSMutableDictionary says:
if theKey is new: the object is retained, but the key is copied
if theKey exists: the previous object is released and
the new object is retained
1. What I am seeing, however, is that if theKey is new, it's retain
count after being copied becomes 2. (If theKey is not new, it's
retain count stays at 1.) Why is the key's retain count incremented
if the key is just copied?
I realize that I could use theKey = [NSString
stringWithCString:mCString] and then not release it in the loop, but
that's a discussion I started in another thread. Either way, I need
to understand how the retain count works and using alloc/init gives
me better control.
2. Is it okay to use @"" for the objects in the loop? Will that
create a new null string for each addition, or reuse the same one?
Is there a better way?
Jeff
_______________________________________________
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.