More memory allocation questions
More memory allocation questions
- Subject: More memory allocation questions
- From: Terry Simons <email@hidden>
- Date: Sun, 28 Jul 2002 14:02:45 -0600
Thanks to everyone who replied to my questions about memory management
in Cocoa.
I want to make sure that I understand the clarifications people made.
Firstly, I definitely am making things harder than they need to be. :)
I've had the following suggestions:
Read stepwise articles. (done)
Read the NSCopying Protocol documentation.
Check out the Foundation Tool template code.
Are there any other Apple documents, or websites that I should look at
in regards to memory management with Cocoa?
People made the following clarifications:
Copying an object ( myObject = [someObject copy] ) is like a C++ copy
constructor (for those familiar with C++), but it may or may not
actually make a copy... especially if the data is immutable it makes
more sense to "retain" the object to save memory, since the data can't
be changed anyway. It also stands to reason that this may improve the
speed of the application, especially if big immutable objects are
"copied".
The memory allocation stuff isn't a part of the Apple runtime, but
rather a mechanism that libraries use.
What exactly is the Apple runtime?
They way I see it now:
Most (all?) of the time an NSAutoreleasePool object is set up for you
every time your program handles an event.
Autoreleasing an object ( [someObject autorelease] ) does nothing other
than add that object to the NSAutoreleasePool object.
At the end of the event loop, any objects in the NSAutoreleasePool
object get a "release" message, which decrements their count, and if the
count is equal to 0, they are dealloc'd.
A "retain" to an object will increment the count of an object, so that
if they are in the autorelease pool when you get access to them, you can
make sure they stay around until you're done with them. (Unless someone
mistakenly sends more release/autorelease messages than they should to
that object).
If you retain an object, then you should release/autorelease it.
It seems that you should always use autorelease, unless you are 100%
certain that nobody else is using a specified object, then release may
be preferable because it will free up resources immediately.
If you don't alloc/init an object, you shouldn't release it.
If you don't autorelease/release objects that you create with alloc/init
then you'll leak memory.
How's that?
Thanks again to everyone that replied to my initial E-mail,
- Terry
_______________________________________________
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.