使用CGContextRef在iOS中记忆泄漏

时间:2012-11-05 05:12:15

标签: ios memory-management memory-leaks core-foundation cgcontextref

我有一组代码,它采用存储在UIImageView中的图像并修改其内容,以便复制到另一个UIImageView的新图像中。问题是,当我分析项目时,此代码始终会从编译器收到内存警告。我试图以各种方式实现此代码,我总是收到一种不同类型的内存警告。编译器的输出表明“调用函数'CGBitMapContextCreateImage'返回一个带有+1保留计数的核心基础对象”,这会导致图像对象的保留计数为+1。如果我自动释放图像对象,编译器会有一个内存警告,表示自动释放被多次调用,并且图像对象最初的保留计数为0.

这两个编译器警告不矛盾吗?如何修复此代码以确保不会发生内存泄漏?

-(UIImage *) makeImageLight{

UIImage * image = self.masterImage.image;

NSUInteger width = image.size.width;
NSUInteger height = image.size.height;
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = width * bytesPerPixel;

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);

CGColorSpaceRelease(colorSpace);

CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = height}, image.CGImage);

UInt8* data = (UInt8*)CGBitmapContextGetData(bmContext);


for (size_t i = 0; i < CGBitmapContextGetWidth(bmContext); i++)
{
    for (size_t j = 0; j < CGBitmapContextGetHeight(bmContext); j++)
    {
        int pixel = j * CGBitmapContextGetWidth(bmContext) + i;

        pixel = pixel * 4;

        UInt8 red = data[pixel + 1];         // If you need this info, enable it
        UInt8 green = data[pixel + 2]; // If you need this info, enable it
        UInt8 blue = data[pixel + 3];    // If you need this info, enable it

        red = ((255 - red) * .3) + red;
        green = ((255 - green) * .3) + green;

        data[pixel + 1] = red;
        data[pixel + 2] = green;
        data[pixel + 3] = blue;

    }
}

// memory warning occurs in the following line:

image = [UIImage imageWithCGImage:CGBitmapContextCreateImage(bmContext)];

CGContextRelease(bmContext);

return image;

}

没关系,我通过添加以下代码来修复它,以释放从Context创建的CGImage:

CGImageRef imageRef = CGBitmapContextCreateImage(bmContext);

image = [UIImage imageWithCGImage:imageRef];

CGImageRelease(imageRef);

1 个答案:

答案 0 :(得分:4)

您使用CGBitmapContextCreateImage()创建CGImage,但您尚未发布该CGImage

您需要按如下方式拆分UIImage创建行:

CGImageRef cgimage = CGBitmapContextCreateImage(bmContext);
image = [UIImage imageWithCGImage:cgimage];
CGImageRelease(cgimage);