以下代码按照我想要的方式工作,但是每次调用它时,Instruments都会告诉我我有一个CGImage内存泄漏。我一直难以理解要发布什么以及何时发布。以下是来自我文件的@interface部分。
CGImageRef depthImageRef;
char *depthPixels;
NSData *depthData;
在下面的代码中,我基本上更改了depthPixels,然后将结果存储在新的depthImageRef中。
size_t width = CGImageGetWidth(depthImageRef);
size_t height = CGImageGetHeight(depthImageRef);
size_t bitsPerComponent = CGImageGetBitsPerComponent(depthImageRef);
size_t bitsPerPixel = CGImageGetBitsPerPixel(depthImageRef);
size_t bytesPerRow = CGImageGetBytesPerRow(depthImageRef);
for (int row = 0; row < height; row += 1) {
for (int bitPlace = 0; bitPlace < bytesPerRow; bitPlace += 4) {
CGPoint pointForHeight = CGPointMake((bitPlace/4) - place.x, row - place.y);
int distanceFromLocation = sqrt(pow(place.x - pointForHeight.x, 2) + pow(place.y - pointForHeight.y, 2));
int newHeight = blopHeight - (5 - sizeSlider.value)*distanceFromLocation;
NSInteger baseBitPlace = row*bytesPerRow + bitPlace;
CGFloat currentHeight = depthPixels[baseBitPlace];
if (newHeight > currentHeight) {
depthPixels[baseBitPlace] = newHeight;
}
}
}
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(depthImageRef);
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, depthPixels, [depthData length], NULL);
depthImageRef = CGImageCreate (
width,
height,
bitsPerComponent,
bitsPerPixel,
bytesPerRow,
colorspace,
bitmapInfo,
provider,
NULL,
false,
kCGRenderingIntentDefault
);
CGColorSpaceRelease(colorspace);
CFRelease(provider);
CGDataProviderRelease(provider);
我相信会造成泄漏,因为我一直在创建depthImageRef但从未释放它。我尝试将CGImageRelease(depthImageRef)放置在各个位置,并将depthImageRef设置为nil,通常当我这样做时会崩溃。谢谢!
最佳答案
如果通过调用上面的代码多次重新创建depthImageRef,则通过重复创建CGImageRefs而不释放它们来泄漏内存。如果要重新创建dataImageRef
,则应在创建新映像之前立即释放旧映像。
// works, even if depthImageRef is NULL such as in the initial case.
CGImageRelease(depthImageRef);
depthImageRef = CGImageCreate ( //...
另外,请确保您在
CGImageRelease
方法中调用dealloc
并释放dealloc中的depthPixels
缓冲区。 CGDataProviderRelease
不会释放传递给它的缓冲区,除非您传递一个回调以释放该缓冲区。由于您正在呼叫CFRelease(provider)
,因此不需要呼叫CGDataProviderRelease(provider)
。