Re: autorelease - when is retain count decremented
Re: autorelease - when is retain count decremented
- Subject: Re: autorelease - when is retain count decremented
- From: David Reed <email@hidden>
- Date: Tue, 14 Sep 2004 17:52:06 -0400
Justin,
I am going to answer your questions point-by-point below, but first a
couple conceptual documentation links that cover this:
"The Objective-C Programming Language: Memory Management" at
<http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/
RuntimeOverview/chapter_4_section_2.html>
"Object Ownership and Disposal" at
<http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/
Concepts/ObjectOwnership.html>
Reading and understanding the documentation on Cocoa memory management
is crucial to being able to develop effectively in Cocoa.
just wondering what causes the retain count of an object to drop.
A -release message being sent. Nothing else. -autorelease merely defers
the release until the current autorelease pool is itself released.
this is the situation I've been wondering about:
NSString *myString = [NSString stringWithFormat:@"testing"];
myString = anotherString;
when I point myString away from the 'testing' string, does the
'testing' memory get freed?
No, you are just assigning the pointer. *If* some memory needs to be
released in this situation, you *must* cause this to occur with either
-release or -autorelease messages. However, in this circumstance, no
release is needed because the return value of +stringWithString: is
already autoreleased.
or should I release myString before pointing it to something else?
If you had explicitly allocated it (via alloc/init or
copy/copyWithZone:), then yes you should. This is not the case in the
above snippet.
also, in this situation do I now have two pointers to the same piece
of memory, and therefore a retain count of two?
While you do have two pointers to the same object, the retain count is
only incremented when you send an object a -retain message. Neither the
C compiler nor the Objective-C runtime does any special "magic" to
handle memory management - it is entirely based on the -retain,
-release, and -autorelease messages.
You just need to understand the object ownership rules and the
reference counting mechanism, and it will all become clear to you.
Hope this helps,
David.
--
David Reed | email@hidden | AIM/iChat: parmadil01
_______________________________________________
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