Re: Memory Managment (copys??)
Re: Memory Managment (copys??)
- Subject: Re: Memory Managment (copys??)
- From: Charlton Wilbur <email@hidden>
- Date: Sun, 6 Feb 2005 22:06:21 -0500
On Feb 6, 2005, at 1:37 PM, Coleman Nitroy wrote:
On Feb 6, 2005, at 11:16 AM, Roarke Lynch wrote:
This code will leak. You should replace the first line in the for
loop with:
object = [[[SOMEObject alloc] init] autorelease];
You need to make sure that any local objects you use are (retain,
alloc, copy) / (autorelease, release) balanced.
Why is a autorelease needed? How exactly does autoreleasing work?
In this case, autoreleasing isn't needed; the code as written works
just fine. (The suggested replacement *also* works just fine, and is
the idiom I'd prefer in a method that returned object. Saying "foo =
[FooClass alloc] init] autorelease];" puts all the object lifetime
management code I need to worry about in one line and makes it apparent
that it's balanced.
When you send an object an autorelease message, it is added to the
current autorelease pool. At some later time, when the autorelease
pool is released, everything in the autorelease pool will be sent a
release message. In Cocoa GUI applications, the "some later time" is
usually the end of the event loop, though you can create your own
autorelease pool in loops that allocate and autorelease a lot of
objects.
The reason autoreleasing is useful is that it saves a lot of worrying
about memory management without requiring garbage collection. The rule
in Cocoa is that allocs + copys + retains and releases + autoreleases
in a particular segment of code must be balanced; as long as you make
sure you call release or autorelease on an object as many times as you
call alloc or copy or retain, you're all set. Without autoreleasing,
you can't do that, because you can't release an object before you
return it - if you did, you'd be returning an invalid object. With
autoreleasing, you are returning an object that will be valid at least
while the autorelease pool exists, which means that any method in the
call stack that finds out about that object can express an interest in
it before it is released and destroyed.
Charlton
--
Charlton Wilbur
email@hidden
email@hidden
_______________________________________________
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