在 dealloc 中将委托设置为 nil [英] Setting delegate to nil in dealloc

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

问题描述

在 Objective-C 中,我理解如果一个对象将自己设置为另一个对象的委托,它应该在其 dealloc 中将该对象的委托设置为 nil 以避免在它消失后收到发送的消息.

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天全站免登陆