Re: Immediate memory release
Re: Immediate memory release
- Subject: Re: Immediate memory release
- From: Graham Cox <email@hidden>
- Date: Thu, 1 May 2008 12:45:02 +1000
Well, because of Matt's post I read up more on autorelease pools. The
docs state:
"If you release an autorelease pool that is not the top of the stack,
this causes all (unreleased) autorelease pools above it on the stack
to be released, along with all their objects. If you neglect to send
release to an autorelease pool when you are finished with it
(something not recommended), it is released when one of the
autorelease pools in which it nests is released.
This behavior has implications for exceptional conditions. If an
exception occurs, and the thread suddenly transfers out of the current
context, the pool associated with that context is released. However,
if that pool is not the top pool on the thread’s stack, all the pools
above the released pool are also released (releasing all their objects
in the process). The top autorelease pool on the thread’s stack then
becomes the pool previously underneath the released pool associated
with the exceptional condition. Because of this behavior, exception
handlers do not need to release objects that were sent autorelease.
Neither is it necessary or even desirable for an exception handler to
send release to its autorelease pool, unless the handler is re-raising
the exception."
So the answer to my question is yes - there is additional magic going
on when exceptions are involved. So in fact despite appearances it
doesn't leak after all.
Cool, I learned something ;-)
G.
On 1 May 2008, at 12:27 pm, Jens Alfke wrote:
On 30 Apr '08, at 5:53 PM, Graham Cox wrote:
If <some code> throws an exception won't that mean that <pool> is
leaked? (and all of its contents up to that point too; applies to
both of our code examples).
Yup. You can work around that by using @finally:
for (i = 0; i < count; i++)
{
NSAutoreleasePool* pool = [NSAutoreleasePool new];
@try{
NSImage* tempSource = [[[NSImage alloc]
initWithContentsOfFile:sPath[i]] autorelease];
// autorelease tempSource to ensure that we get cleaned up
if anything in 'some code' throws an exception.
// pool will automagically be released later if an exception
does happen and [pool release] get bypassed.
// some code
}@finally{
[pool drain];
}
}
I also changed the pool calls to the current recommended names: +new
and -drain.
—Jens
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden