Search code examples
objective-cmemory-leaksosx-lionnsoperationnsimage

How to stop NSImage lockfocus from Leaking Memory in an NSOperation?


I have a problem with NSImages leaking memory when I draw to them with lock/unlockfocus. The leak goes away when I comment out the LEAKS HERE code below. So I know that is where the leak is happening.

for(int i= 0; i < nNumberImages; ++i)
{
    m_apNSImageArray[i]= [[NSImage alloc] initWithSize:m_viewRect.size];        
    if(!m_apNSImageArray[i])
    {
        return;
    }  

    //LEAKS IN THIS CODE HERE
    [m_apNSImageArray[i] lockFocus];

    //EDIT: Commented the lines below out, but leak persists.    
    //[[[[NSApp delegate] getColors] getAudioWaveColor:YES] setStroke];        
    //[[m_pmaBezierPaths objectAtIndex:i] stroke];    

    [m_apNSImageArray[i] unlockFocus];      
    //TO HERE        
}

I'm using garbage collection, and this for-loop is part of an NSOperation running in an NSOperationQueue in OSX 10.7 Lion.

Is this a bug with NSImage's lockfocus on background threads/operations?

EDIT: It appears that lockFocus is allocating new space each time its called.


Solution

  • Well I still am not totally sure how to stop the leak completely, but I drastically reduced the number of times I lockFocus/unlockFocus. This essentially solved my problem.