NSImage和相关的API泄漏内存

时间:2010-08-06 15:15:22

标签: macos cocoa nsimage

以下是我的代码段:

 // Make Auto release pool
 NSAutoreleasePool * autoReleasePool = [[NSAutoreleasePool alloc] init];
 try
 {
  if (mCapture)
  {
   // Get the image reference
   NSImage* image = NULL;
   image = [mCapture getCurrentFrameImage];

   // Get the TIFF data
   NSData *pDataTifData = [[NSData alloc] initWithData:[image TIFFRepresentation]]; 
   NSBitmapImageRep *pBitmapImageRep = [[NSBitmapImageRep alloc] initWithData:pDataTifData];

   // Convert to BMP data
   NSData *pDataBMPData; 
   pDataBMPData = [pBitmapImageRep representationUsingType: NSPNGFileType
               properties: nil];

   // Save to specified path
   ASL::String strPath =  ASL::MakeString(capInfo->thefile.name);
   NSString* pPath = (NSString*)ASL::MakeCFString(strPath);
   [pDataBMPData writeToFile:pPath
         atomically: YES];

   ::CFRelease(pPath);
   pDataBMPData = nil;

   [pBitmapImageRep release];
   pBitmapImageRep = nil;
   [pDataTifData release];
   pDataTifData = nil;

   image = nil;
  }
 }
catch(...)
{
}
[autoReleasePool drain];

请注意,image = [mCapture getCurrentFrameImage];正在返回自动释放的NSImage。我正在发布对象并且还有NSAutoreleasePool。但是每次执行此代码片段时,它仍会泄漏大约3-4 MB的内存。我不确定错误在哪里。

1 个答案:

答案 0 :(得分:1)

您可以通过使captureCurrentFrameImage返回NSBitmapImageRep而不是NSImage来简化此代码,因为您实际上从未在此处使用NSImage。您可以在必要时将图像rep包装在图像中,对于此代码,只需单独使用图像rep来生成PNG数据。除此之外,这可以节省您通过TIFF表示的旅行。

如果在进行这些更改后仍然泄漏,请在Instruments的Leaks模板下运行您的应用程序;该模板中的两个工具Leaks和ObjectAlloc将帮助您找到任何泄漏。