使用委托模式时避免EXC_BAD_ACCESS [英] Avoiding EXC_BAD_ACCESS when using the delegate pattern

查看:132
本文介绍了使用委托模式时避免EXC_BAD_ACCESS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A有一个视图控制器,它创建一个下载器对象,它具有对视图控制器的引用(作为委托)。如果成功下载项目,下载程序将回调视图控制器。只要您保持在视图上,这样就可以正常工作,但如果您在下载完成之前离开,我会获得 EXC_BAD_ACCESS 。我理解为什么会发生这种情况,但有没有办法检查对象是否仍然被分配?
我尝试使用委托!= nil [委托respondsToSelector:] 进行测试,但它扼杀了。

A have a view controller, and it creates a "downloader" object, which has a reference to the view controller (as a delegate). The downloader calls back the view controller if it successfully downloads the item. This works fine as long as you stay on the view, but if you navigate away before the download is complete I get EXC_BAD_ACCESS. I understand why this is happening, but is there any way to check if an object is still allocated? I tried to test using delegate != nil, and [delegate respondsToSelector:], but it chokes.

if (!self.delegate || ![self.delegate respondsToSelector:@selector(downloadComplete:)]) {
  // delegate is gone, go away quietly
        [self autorelease];
        return;
    }
else {
  // delegate is still around
  [self.delegate downloadComplete:result];
}

我知道我可以,

a)让下载程序对象保留视图控制器

a) have the downloader objects retain the view controller

b)在视图控制器中保留一组下载程序,并将其委托值设置为nil取消分配视图控制器。

b) keep an array of downloaders in the view controller, and set their delegate values to nil when I deallocate the view controller.

但我想知道是否有更简单的方法,我只测试委托地址是否包含有效对象?

But I wonder if there is an easier way, where I just test if the delegate address contains a valid object?

推荐答案

不,你不能(有用)测试地址是否包含有效对象。即使您能够在内存分配系统的内部进行grub并确定您的地址指向有效对象,这也不一定意味着它是您之前引用的相同的对象to:对象可能已被释放,另一个对象在同一内存地址创建。

No, you can't (usefully) "test if an address contains a valid object". Even if you were able to grub around inside the internals of the memory allocation system and determine that your address points to a valid object, that would not necessarily mean that it was the same object that you were previously referring to: the object could have been deallocated and another object created at the same memory address.

保留委托是解决此问题的常用方法。您的选项(b)会破坏对象封装,并可能存在线程安全问题。

Retaining the delegate is the usual way to solve this. Your option (b) breaks object encapsulation, and might have thread-safety issues.

这篇关于使用委托模式时避免EXC_BAD_ACCESS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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