I've been trying to debug memory leaks in an objective-c program for the last couple of days and was playing around with some very basic sample code to test some ideas and came across something that seems to be a bug to me but wanted to get some opinions from those with more knowledge when it comes to developing in the Mac world.
I have the following bit of code:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRect desktopRect = NSZeroRect;
NSArray* screens = [[NSScreen screens] autorelease];
int x = 0;
for (x = 0; x < [screens count]; x++)
{
NSScreen *screen = [screens objectAtIndex:x];
}
[pool drain];
This code lives inside a method that I am calling from a while loop that continues until I kill the process. (Remember this is just a simple test.)
When I run this loop and watch allocations in Instruments things work perfectly fine when I am not implementing Garbage Collection. My overall number of allocations stays constant and everything with the NSScreens are getting cleaned up and released.
As soon as I enable Garbage Collection, the call to [NSScreen screens] starts leaking core graphics ob开发者_JAVA技巧jects like mad by never releasing them.
I have seen in other forums where people a few years back talked about Core Graphics being very leaky under Garbage Collection. I'm wondering if that is the case here as well.
Any thoughts from the community?
Ok, I'm going to go out on a limb here and say that yes it is a bug on Apples part though I did find a solution using some Toll-Free-Bridging magic. I modified the code to be:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRect desktopRect = NSZeroRect;
CFArrayRef screens = CFMakeCollectable((CFArrayRef)[NSScreen screens]);
int x = 0;
for (x = 0; x < [screens count]; x++)
{
NSScreen *screen = (NSScreen*)CFArrayGetValueAtIndex(screens,x);
}
[pool drain];
By calling CFMakeCollectable on the toll-free-bridged array, it allowed the background core graphics objects to be properly cleaned up when using garbage collection.
This definitely makes me think that Apple needs to do some more work with Garbage Collection and Cocoa objects that wrap Core Graphics.
精彩评论