0

我有这个代码:

 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 [掩码释放]不工作......面具不是一个指针......我该如何解决这个泄漏?

4

2 回答 2

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;
}
于 2011-07-07T00:03:27.910 回答
1

使用CGImageRelease(mask)CGImageMaskCreate 返回一个保留计数为 1 的 CGImageRef。

于 2011-06-05T22:08:50.603 回答