我有这段代码:
Texture2D *cachedTexture;
if(cachedTexture = [cachedTextures objectForKey:aName]) {
return cachedTexture;
}
// We are using imageWithContentsOfFile rather than imageNamed, as imageNamed caches the image in the device.
// This can lead to memory issue as we do not have direct control over when it would be released. Not using
// imageNamed means that it is not cached by the OS and we have control over when it is released.
NSString *filename = [aName stringByDeletingPathExtension];
NSString *filetype = [aName pathExtension];
NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:filetype];
UIImage *maskImage=[UIImage imageWithContentsOfFile:path];
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
cachedTexture = [[Texture2D alloc] initWithMask:mask filter:aFilter];
[cachedTextures setObject:cachedTexture forKey:aName];
静态分析器写道: 1)调用函数CGImageMaskCreate返回一个带有+1保留计数器的核心基础对象 2)分配并存储到掩码中的对象稍后在此执行路径中未被引用,并且具有+1的保留计数器 [面具释放]不起作用......面具不是一个很好的... 我该如何解决这个漏洞?
答案 0 :(得分:5)
这是一个非泄漏的util方法,可以满足你的需要:
- (UIImage*) maskImage:(UIImage *)image
withMask:(UIImage *)maskImage
{
CGImageRef imageRef = image.CGImage;
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef),
NULL, // decode should be NULL
FALSE // shouldInterpolate
);
CGImageRef masked = CGImageCreateWithMask(imageRef, mask);
CGImageRelease(mask);
UIImage *maskedImage = [UIImage imageWithCGImage:masked];
CGImageRelease(masked);
return maskedImage;
}
答案 1 :(得分:1)
使用CGImageRelease(mask)
CGImageMaskCreate返回保留计数为1的CGImageRef。