Search code examples
objective-cxcodensimage

Memory leaks while using NSReadPixel in a cycle


I’m trying to call this method in a cycle and everything works fine until I increase number of iterations up to a couple of thousands. Then it takes more than 1 GB of memory that returns after the end of a cycle. How to avoid that loss?

- (char) getPixelColorAtLocation: (CGPoint)point {

NSImage *image = sampleImageView.image;
[image lockFocus];
NSColor *aColor = NSReadPixel(point);
[image unlockFocus];

return 'r’; // just for debugging 
//some code here
}

Oh, moving the -lockFocus outside the method was really easy, great thanks!


Solution

  • Calling -lockFocus causes a snapshot of the image to be made. It's not something to be done lightly. Move the locking and unlocking of focus outside of the tight loop and you should be fine.

    Alternately, you could work out another way to read pixel data out of images. Unfortunately, it turns out that that's a little harder than it seems like it ought to be. If it were me, I would create a CGBitmapContext with a specific, pre-allocated backing memory, draw the image into that, then read the pixel data out based on your knowledge of the backing memory format that you specified when you created the context. It's not impossible, but it's nowhere near as simple as calling NSReadPixel.

    It occurs to me... you could also wrap the body of your method in an @autoreleasepool. This would prevent the huge memory growth, but the performance is going to be abysmal because every call to the method is going make a new snapshot of the image, etc. For future readers, don't do this, but in the interest of completeness, it would solve the memory portion of the problem.