ios - 如何在接收方法中快速释放内存?
<p><p>在我的 iPhone 应用程序中,我有一个缓存到磁盘的大图像,我在将图像交给一个对该图像进行大量处理的类之前检索它。接收类只需要简单的图像进行一些初始化,我想尽快释放图像占用的内存,因为图像处理代码非常占用内存,但我不知道如何。</p>
<p>看起来像这样:</p>
<pre><code>// inside viewController
- (void) pressedRender
{
UIImage *imageToProcess = [ imageForKey:@"reallyBigImage"];
UIImage *finalImage = ;
// save the image
}
// inside frameBuffer class
- (UIImage *)renderImage:(UIImage *)startingImage
{
CGContextRef context = CGBitmapCreateContext(....)
CGContextDrawImage(context, rect, startingImage.CGImage);
// at this point, I no longer need the image
// and would like to release the memory it's taking up
// lots of image processing/memory usage here...
// return the processed image
CGImageRef tmpImage = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *renderedImage = ;
CGImageRelease(tmpImage);
return renderedImage;
}
</code></pre>
<p>这可能很明显,但我遗漏了一些东西。谢谢。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>@Jonah.at.GoDaddy 走在正确的轨道上,但我会让所有这些更明确,而不是依赖 ARC 优化。 ARC 在 Debug模式下的攻击性要小得多,因此除非您采取措施,否则在调试时您的内存使用量可能会变得过高。</p>
<pre><code>UIImage *imageToProcess = [ imageForKey:@"reallyBigImage"];
</code></pre>
<p>首先,我将假设 <code>imageForKey:</code> 本身不缓存任何内容,也不调用 <code>imageNamed:</code> (它会缓存内容)。</p>
<p>关键是当你希望内存消失时,你需要将指针置零。如果您将图像从一个地方传递到另一个地方,那将非常困难(Jonah 的解决方案也解决了这个问题)。就个人而言,我可能会做这样的事情来尽可能快地从图像->上下文中获取:</p>
<pre><code>CGContextRef CreateContextForImage(UIImage *image) {
CGContextRef context = CGBitmapCreateContext(....)
CGContextDrawImage(context, rect, image.CGImage);
return context;
}
- (void) pressedRender {
CGContextRef context = NULL;
// I'm adding an @autoreleasepool here just in case there are some extra
// autoreleases attached by imageForKey: (which it's free to do). It also nicely
// bounds the references to imageToProcess.
@autoreleasepool {
UIImage *imageToProcess = [ imageForKey:@"reallyBigImage"];
context = CreateContextForImage(imageToProcess);
}
// The image should be gone now; there is no reference to it in scope.
UIImage *finalImage = ;
CGContextRelease(context);
// save the image
}
// inside frameBuffer class
- (UIImage *)renderImageForContext:(CGContextRef)context
{
// lots of memory usage here...
return renderedImage;
}
</code></pre>
<p>对于调试,您可以通过向其添加关联的观察程序来确保 <code>UIImage</code> 真的消失了。查看接受的答案 <a href="https://stackoverflow.com/questions/19298084/how-to-enforce-using-retaincount-method-and-dealloc-selector-under-arc" rel="noreferrer noopener nofollow">How to enforce using `-retainCount` method and `-dealloc` selector under ARC?</a> (答案与问题无关;它恰好解决了您可能会发现有用的相同问题)。</p></p>
<p style="font-size: 20px;">关于ios - 如何在接收方法中快速释放内存?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/20645857/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/20645857/
</a>
</p>
页:
[1]