在dealloc中将代理设置为nil [英] Setting delegate to nil in dealloc

查看:114
本文介绍了在dealloc中将代理设置为nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,我明白如果一个对象将自己设置为另一个对象的委托,那么它应该将该对象的委托设置为 nil c> dealloc 以避免在消失后发送消息。

In Objective-C, I understand that if an object sets itself as the delegate of another object, it should set that object's delegate to nil in its dealloc to avoid getting sent messages after it's gone.

但是,当使用Accessorizer(Xcode实用程序)时,它生成的存根代码还在具有委托实例变量的类的 dealloc 中放置一个 delegate = nil 。这是什么目的?

However, when using Accessorizer (an Xcode utility), the stub code it generates also puts a delegate = nil in the dealloc of the class that has the delegate instance variable. What is the purpose of that?

推荐答案

这是一个防御性的编程动作。清除对代理对象的引用,在对象尝试访问代理之后,告诉您完成该代理。作为您的dealloc的一部分,您可能有一种方法或者做一些触发KVO通知的方法,该通知可以调用委托。因此,将代理的引用设置为nil可防止发生这种情况。如果发生这种情况,你可能会遇到一些奇怪的事故,这是很有趣的重现和修复。

It's a defensive programming move. It's clearing out the reference to the delegate object incase something else in your object tries to access the delegate after you've told it that you're done with it. As part of your dealloc you might have a method or do something that triggers a KVO notification that makes a call to the delegate. So setting the delegate's reference to nil prevents that from happening. If it did happen you could end up with some oddball crashes that are fun to reproduce and fix.

这篇关于在dealloc中将代理设置为nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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