Stack-based C++ class to wrap NSAutoreleasePool
Stack-based C++ class to wrap NSAutoreleasePool
- Subject: Stack-based C++ class to wrap NSAutoreleasePool
- From: Dan Korn <email@hidden>
- Date: Wed, 11 Nov 2009 11:17:25 -0600
I'm building a Framework with some exported extern "C" functions in
Objective-C++, based on this example:
http://developer.apple.com/internet/webservices/webservicescoreandcfnetwork.html
Because this is a Framework, it doesn't have its own main() function
to set up an NSAutoreleasePool. So I need a way to free the memory
used by the Cocoa objects in the Framework when I'm done with it. I
first tried to rework the code to not use garbage collection, but that
wasn't working.
Since each call into the Framework is basically self-contained with a
plain old "C" interface, I thought, why not just add an
NSAutoreleasePool to each function, and have it drain when the
function returns? But I didn't want to have to go through the code
and add a call to [pool drain] before every return path. So, I
figured, why not do this?
class CAutoreleasePool
{
NSAutoreleasePool *pool;
public:
CAutoreleasePool()
{
pool = [[NSAutoreleasePool alloc] init];
}
~CAutoreleasePool()
{
[pool drain];
}
};
#define StackAutoreleasePool() CAutoreleasePool _temp
Then all I need to do is declare "StackAutoreleasePool();" at the top
of each exported function. It seems to work just fine and prevent
leaks.
From a C++ point of view, this is intuitive, so I figure that I can't
the first one to have this idea, but I looked around for a similar
solution and didn't find any. And I'm new to Cocoa and Objective-C,
so it's entirely possible I'm missing some pitfall with this strategy.
So, is there any reason why I shouldn't do this?
Thanks,
Dan
_______________________________________________
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