何时回调已解除分配的委托? [英] handle when callback to a dealloced delegate?

查看:26
本文介绍了何时回调已解除分配的委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个类之间实现了委托回调模式,但没有保留委托.但在某些情况下,委托被解除分配.

I implemented the delegate-callback pattern between two classes without retaining the delegate. But in some cases, the delegate is dealloced.

(我的情况是我有一个 ViewController 是委托对象,当用户按下后退按钮将该 ViewController 从 NavigationController 堆栈中弹出时)

(My case is that I have a ViewController is the delegate object, and when the user press back button to pop that ViewController out of the NavigationController stack)

然后回调方法get BAD_EXE:

Then the callback method get BAD_EXE:

if (self.delegate != nil && [self.delegate respondsToSelector:selector]) {
    [self.delegate performSelector:selector withObject:self withObject:returnObject];
} 

我知道委托回调模式在很多应用程序中都实现了.您对此有何解决方案?

I know the delegate-callback pattern is implemented in a lot of application. What is your solution for this?

推荐答案

通常,委托应始终在其 dealloc 方法中将其与其委托对象解除关联.所以你的视图控制器应该检查它的 dealloc 是否被设置为委托类的委托,如果是,将委托属性设置为 nil.

Generally, a delegate should always deassociate it from its delegating object in its dealloc method. So your view controller should check in its dealloc whether it is set as the delegate of the delegating class, and if so, set the delegate property to nil.

在大多数情况下,我认为这不会成为问题,因为委托通常是委托对象的唯一所有者.因此,当委托被解除分配时,委托对象也将被解除分配.毕竟,这就是委托对象通常只持有对其委托的弱引用的原因.

In most cases, I would imagine this would not be a problem because very often the delegate is the sole owner of the delegating object. So when the delegate gets deallocated, the delegating object would get deallocated too. After all, this is the reason that delegating objects usually only hold weak references to their delegates.

这篇关于何时回调已解除分配的委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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