Re: Retain counts with a dictionary
Re: Retain counts with a dictionary
- Subject: Re: Retain counts with a dictionary
- From: Greg Titus <email@hidden>
- Date: Sat, 15 Mar 2003 18:28:53 -0800
On Saturday, March 15, 2003, at 05:25 PM, Jeffrey Mattox wrote:
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.
First of all, you probably want to use an NSMutableSet for this
purpose, instead of an NSDictionary.
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.
You are seeing an optimization that NSString is doing. When an NSString
gets the -copy method, it knows that it itself is immutable, so rather
than creating another whole object, it can just return itself with its
retain count incremented. The effect is exactly the same.
If you used NSMutableStrings instead, you'd see a "real" copy made,
since that sort of optimization is invalid for objects which can change.
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?
Yep, it's okay. It should use the same null string for each.
Hope this helps,
- Greg
_______________________________________________
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.