Re: Exceptions and autorelease pools
Re: Exceptions and autorelease pools
- Subject: Re: Exceptions and autorelease pools
- From: Ken Thomases <email@hidden>
- Date: Tue, 06 Dec 2011 15:59:29 -0600
On Dec 6, 2011, at 2:47 PM, Larry Campbell wrote:
> void allocAndRaise()
> {
> [[[NSString alloc] initWithString:@"foo bar and zot"] autorelease];
> [NSException raise:@"foo" format:@"bar"];
> }
>
> //#define LEAK
>
> void foo()
> {
> NSAutoreleasePool *pool = [NSAutoreleasePool new];
> NS_DURING {
> allocAndRaise();
> } NS_HANDLER {
> #ifdef LEAK
> [localException raise];
> #else
> [localException retain]; // I don't think this workaround should be necessary, but it is
> [pool release];
> [[localException autorelease] raise];
> #endif
> } NS_ENDHANDLER
> [pool release];
> }
The workaround is necessary because the exception object raised in allocAndRaise() has been autoreleased. It is no longer owned by anything and is only still around because the pool containing the pending release(s) has not been drained. When you drain it, that executes the pending release(s) and ultimately deallocates it.
That is one of the reasons you are discouraged from releasing/draining autorelease pools in exception handlers or @finally blocks.
As Greg Parker said, the "#ifdef LEAK" code is preferred and will not leak the objects that have been autoreleased.
Regards,
Ken
_______________________________________________
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