处理当回调到一个被释放的委托? [英] handle when callback to a dealloced delegate?

查看:157
本文介绍了处理当回调到一个被释放的委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个类之间实现了委托 - 回调模式,而不保留委托。但在某些情况下,代表被解雇。

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

(我的例子是我有一个ViewController是委托对象,当用户按下后退按钮来从NavigationController堆栈中弹出ViewController)

(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)

然后回调方法得到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天全站免登陆