Le 14 nov. 2009 à 11:47, Roni Music a écrit : > >> 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? > > I've used this approached for many years whenever I have to use Cocoa stuff > in my Carbon C++ apps. > It seems to work perfect. > This RAII (Resource Acquisition Is Initialization) thing is one of the few > things > I really miss when doing plain Cocoa/Obj-C programming. > > Rolf
In fact, this trick is possible in plain Obj-C too (with macros and a little help from the compiler): http://kickingbear.com/blog/archives/13 -- Jean-Daniel _______________________________________________ Cocoa-dev mailing list ([email protected]) 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 [email protected]
