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 (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to