带有CGContexTref的iOS内存泄漏



我有一组代码,该代码将存储在uiimageview中的图像和修改的内容,以将其复制到其他UIImageView的新图像中。问题在于,当我分析项目时,该代码总是会从编译器中收到内存警告。我试图以多种方式实现此代码,最终总是收到其他类型的内存警告。编译器的输出表示"呼叫函数'CGBITMAPCONTEXTCREATEEIMAGE'返回具有 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;
}

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

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

您使用cgbitmapcontextcreateimage()创建一个cgimage,但是您尚未发布该cgimage

您需要按以下方式拆分UIImage创建线:

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

最新更新