ios - iOS 中的内存泄漏与 CGContextRef
<p><p>我有一组代码获取存储在 UIImageView 中的图像并修改其内容以复制到不同 UIImageView 的新图像中。问题是当我分析项目时,这段代码总是从我的编译器收到内存警告。我尝试以多种方式实现此代码,但我总是收到不同类型的内存警告。编译器的输出显示“调用函数 'CGBitMapContextCreateImage' 返回一个具有 +1 保留计数的核心基础对象”,这导致图像对象的保留计数为 +1。如果我自动释放图像对象,编译器会发出内存警告,自动释放被调用多次,并且图像对象最初的保留计数为 0。</p>
<p>这两个编译器警告不是矛盾的吗?如何修复此代码以确保不会发生内存泄漏?</p>
<pre><code>-(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; // If you need this info, enable it
UInt8 green = data; // If you need this info, enable it
UInt8 blue = data; // If you need this info, enable it
red = ((255 - red) * .3) + red;
green = ((255 - green) * .3) + green;
data = red;
data = green;
data = blue;
}
}
// memory warning occurs in the following line:
image = ;
CGContextRelease(bmContext);
return image;
}
</code></pre>
<p>没关系,我通过添加以下代码来修复它以释放从上下文创建的 CGImage:</p>
<pre><code>CGImageRef imageRef = CGBitmapContextCreateImage(bmContext);
image = ;
CGImageRelease(imageRef);
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您使用 CGBitmapContextCreateImage() 创建了一个 CGImage,但您还没有发布该 CGImage</p>
<p>您需要将<code>UIImage</code>创建行拆分如下:</p>
<pre><code>CGImageRef cgimage = CGBitmapContextCreateImage(bmContext);
image = ;
CGImageRelease(cgimage);
</code></pre></p>
<p style="font-size: 20px;">关于ios - iOS 中的内存泄漏与 CGContextRef,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/13226268/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/13226268/
</a>
</p>
页:
[1]