为什么如果对象将要被销毁,我们将委托设为nil在dealloc? [英] Why do we set delegate to nil at dealloc if the object is going to be destroyed anyway?

查看:227
本文介绍了为什么如果对象将要被销毁,我们将委托设为nil在dealloc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

-(void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    PO(NSStringFromCGPoint(self.tableView.contentOffset));
    PO(NSStringFromUIEdgeInsets(self.tableView.contentInset));

    while(false);
}

-(void)dealloc
{
    PO(NSStringFromClass([self class]));
    PO(@"Deallocated");
    self.tableView.delegate=nil;
}

这里我需要设置self.tableView.delegate = nil以避免错误。

Here I need to set self.tableView.delegate = nil to avoid error.

我知道,从我以前的问题,当委托被销毁时,self.tableView.delegate不会自动变为nill。这是因为委托的类型是分配引用而不是弱引用。

I am aware, from my previous question, that self.tableView.delegate won't automatically become nill when the delegate is destroyed. That's because the type of delegate is assign reference instead of weak reference.

然而,self.tableView呢?

However, what about self.tableView?

唯一有很强的参考self.tableView的是它是由self和self itsef拥有的superview。

The only thing with strong reference to self.tableView is it's superview that's owned by self and self itsef.

所以当自我破坏时,self.tableView应该被破坏那么这意味着self.tableView.delegate也会消失。

So when self is destroyed, self.tableView should be destroyed too and that means self.tableView.delegate will be gone too.

所以为什么需要设置 self.tableView.delegate = nil ;

So why do I need to set self.tableView.delegate=nil;

推荐答案

如果您持有self.tableView的唯一参考,则无需设置代理

If you hold the only reference to self.tableView, there's no need of setting the delegate to nil.

唯一需要将委托设置为nil的情况,如果是另一个类,则将您的类作为委托,因为如果您的类被销毁,那么其他班级会寻找你的班级来实施一些方法,你的电话不会在那里。

The only situation where you have to set the delegate to nil, if is another class has your class as a delegate, because if your class is destroyed, that other class will look for your class to implement some methods, and your call won't be there.

这篇关于为什么如果对象将要被销毁,我们将委托设为nil在dealloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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