来自CGImageRef的UIImage [英] UIImage from CGImageRef

查看:111
本文介绍了来自CGImageRef的UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个更复杂的项目尝试一个简单的测试但我感到困惑的是为什么下面的代码崩溃并给出一个EXC_BAD_ACCESS错误?

I am trying a simple test for a much more complex project but I am baffled as to why the code below is crashing and giving an EXC_BAD_ACCESS error?

这是从UIView调用的。

This is called from a UIView.

 - (void)testing {
      NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ball.png" ofType:nil];
      CGImageRef imageRef = [[[UIImage alloc]initWithContentsOfFile:imagePath]CGImage];
 //   CGImageRetain(imageRef);

      UIImage *newImage = [[UIImage alloc]initWithCGImage:imageRef];
      UIImageView *iv = [[UIImageView alloc]initWithImage:newImage];
      [self addSubview:iv];
 }

我的猜测是CGImageRef没有被保留但是添加了CGImageRetain(imageRef) ;没有区别。

My guess is that the CGImageRef is not being retained but adding CGImageRetain(imageRef); makes no difference.

我还应该注意到这个项目已经开启了ARC。

I should also note that this project has ARC turned on.

编辑

EDIT

我做了一些测试,发现这与ARC直接相关因为我创建了2个基本项目,包括上面的代码。 ARC的第一个关闭,它完美地工作。下一次打开ARC并且BAM崩溃并出现相同的错误。有趣的是,我在崩溃前第一次运行项目时遇到了实际的日志错误。

I did a little bit more testing and have discovered that this is directly related to ARC as I created 2 basic projects including only the code above. The first with ARC turned off and it worked perfectly. The next with ARC turned on and BAM crash with the same error. The interesting thing is that I got an actual log error ONLY the first time I ran the project before the crash.

 Error: ImageIO: ImageProviderCopyImageBlockSetCallback 'ImageProviderCopyImageBlockSetCallback' header is not a CFDictionary...


推荐答案

这一行是问题所在:

CGImageRef imageRef = [[[UIImage alloc]initWithContentsOfFile:imagePath]CGImage];

创建的 UIImage 将立即发布这个完整的表达(例如在此行之后)。因此,即使尝试在之后添加 CGImageRetain()也行不通。

The created UIImage will be released immediately following this full-expression (e.g. after this line). So even trying to add a CGImageRetain() afterwards won't work.

根本问题是<$从$ code> CGImage 返回的c $ c> CGImageRef 几乎可以肯定是 UIImage 的ivar当 UIImage 被解除分配时将被释放。

The fundamental problem is the CGImageRef returned from CGImage is almost certainly an ivar of the UIImage and will be released when the UIImage is deallocted.

解决此问题的一般方法是延长生命周期的UIImage 。你可以把 UIImage 放到一个局部变量中并在你最后一次引用 CGImage 之后引用它(例如使用(void)uiimageVar )。或者,您可以在同一行保留 CGImageRef ,例如

The generic way to fix this is to extend the lifetime of the UIImage. You can do this by placing the UIImage into a local variable and referencing it after your last reference to the CGImage (e.g. with (void)uiimageVar). Alternatively, you can retain the CGImageRef on that same line, as in

CGImageRef imageRef = CGImageRetain([[[UIImage alloc] initWithContentsOfFile:imagePath] CGImage]);

但如果你这样做,别忘了发布 imageRef 完成后。

But if you do this, don't forget to release the imageRef when you're done.

这篇关于来自CGImageRef的UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆