【问题标题】:Retain ownership of UIImage created with UIGraphicsGetImageFromCurrentImageContext保留使用 UIGraphicsGetImageFromCurrentImageContext 创建的 UIImage 的所有权
【发布时间】:2010-12-16 18:29:36
【问题描述】:

我正在使用此代码在不同时间获取窗口的屏幕截图,并将创建的 UIImage 放入一个数组中,该数组传递给另一个 UIViewController,以便它们可以全部显示在网格中。我尝试释放 UIImage 并且内存使用量永远不会下降......我怎样才能在这里使用图像一次,并保留所有权,这样我就可以在显示内存后释放内存

UIGraphicsBeginImageContext(self.window.bounds.size);
[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[imagesArray addObject:image];
[image release];

【问题讨论】:

  • UIImage *scaledImage = [UIGraphicsGetImageFromCurrentImageContext() 保留];这会有帮助吗??

标签: iphone memory-management uiimage screenshot


【解决方案1】:

UIGraphicsGetImageFromCurrentImageContext() 返回“一个autoreleased图像对象,其中包含当前位图图形上下文的内容。”

当您将图像添加到 imagesArray 时,NSMutableArray 会对其进行保留,并且 这就是你所需要的。当图像从数组中移除时,内存将被释放。

不应在图片上调用 release。

【讨论】:

    【解决方案2】:

    我在 UIGraphicsGetImageFromCurrentImageContext() 上发生了内存崩溃...如果您要创建和释放大量它们,则应在每次迭代时将它们包装在新的 AutoReleasePool 中。即使允许 NSRunLoop 打勾,也不足以让 Apple/iOS 对其周围的垃圾进行整理。

    例如

    for( ... )
    {
       @autoreleasepool
       {
          UIImage* blah = UIGraphicsGetImageFromCurrentImageContext();
       }
    }
    

    【讨论】:

      【解决方案3】:

      我在后台线程中使用来自 UIGraphicsGetImageFromCurrentImageContext() 的保留 UIImage 图像遇到了奇怪的 UIImage 内存泄漏。问题原来是你应该只从应用程序的主线程调用这个函数。小心。

      【讨论】:

      • 根据 Apple 文档,“可以从应用程序的任何线程调用此函数。”你如何确认它只能从主线程调用?
      猜你喜欢
      • 2017-02-27
      • 1970-01-01
      • 2011-11-18
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 2022-01-20
      • 1970-01-01
      相关资源
      最近更新 更多