Re: Retain counts with a dictionary
Re: Retain counts with a dictionary
- Subject: Re: Retain counts with a dictionary
- From: Nicholas Riley <email@hidden>
- Date: Sat, 15 Mar 2003 20:20:15 -0600
- Mail-followup-to: Jeffrey Mattox <email@hidden>, email@hidden
On Sat, Mar 15, 2003 at 07:25:02PM -0600, Jeffrey Mattox wrote:
>
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?
These two statements are not inconsistent. A class is permitted to
implement the -copy method any way it wants to; in the case of a class
of immutable objects such as NSString, this includes simply retaining
itself. Since there's no way you can change the NSString such that
its hash value is different, there's no reason to make a true copy of
the object.
Here's an example - this is F-Script, hopefully the Smalltalk/ObjC
syntax differences will not be too hard to understand.
>
dict := NSMutableDictionary alloc init
>
y := 'hi'. z := 'hi'
>
y == z
false
>
dict setObject: '' forKey: y
>
y retainCount
2
>
dict setObject: '' forKey: z
>
z retainCount
1
>
dict allKeys
NSCFArray {'hi'}
>
dict allKeys at: 0
'hi'
>
(dict allKeys at: 0) == y
true
Here's how NSString behaves when you send it 'copy':
>
yy := y copy
>
yy
'hi'
>
yy == y
true
>
y retainCount
4
>
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.
Doing what you're doing is better, because it doesn't cause the
additional overhead of adding each string to the autorelease pool.
>
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?
If you don't ever use the dictionary to do mapping per se, use a
NSMutableSet instead. It has dictionary-like performance in checking
for an object's existence but doesn't perform any mapping.
--
=Nicholas Riley <email@hidden> | <
http://www.uiuc.edu/ph/www/njriley>
Pablo Research Group, Department of Computer Science and
Medical Scholars Program, University of Illinois at Urbana-Champaign
_______________________________________________
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.