在dealloc时在self上调用方法 [英] Calling a method on self while in dealloc

查看:385
本文介绍了在dealloc时在self上调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要释放的对象字典.我有一个方法可以对整个字典执行此操作.在用-dealloc方法发布字典之前,我想做同样的事情.但是,我不确定释放过程中对象的状态.例如,在C#或Java中,我永远不会在要完成的对象上调用方法,但是我不确定这是否适用于Objective C和释放.在释放过程中在self上调用clean方法是否可以接受,还是应该在-dealloc中复制该功能?

I have a dictionary of objects that need to be cleaned up before they are released. I have a method that does this for the entire dictionary. Before I release the dictionary in my -dealloc method, I want to do the same thing. However, I am not sure of the state of the object during deallocation. In C# or Java, for instance, I would never call a method on the object being finalized, but I am not sure this applies to Objective C and deallocation. Is it acceptable to call the clean up method on self during deallocation, or should I duplicate that functionality in my -dealloc?

推荐答案

是的,您可以从dealloc方法内部调用方法,尽管谨慎选择是明智的.应该调用的 only 方法几乎应该是拆卸"方法,或者是在回收对象资源之前帮助清理对象的方法.这些清除方法包括:

Yes, you may invoke methods from inside your dealloc method, though you're wise to be cautious. Pretty much the only methods you should invoke should be "tear down" methods, or methods that help in cleaning up an object before its resources are reclaimed. Some of these cleanup methods include:

  • 通过通知中心取消注册通知
  • 让自己成为键值观察者
  • 其他常规清除方法

但是,请注意,在每种方法中,您的对象都将处于不一致状态.它可能会部分解除分配(某些ivars可能/将无效),因此您应该从不依赖特定的对象状态.这些方法应该用于继续解构对象状态.

Note, however, that in each of these methods, your object will be in an inconsistent state. It may be partially deallocated (some ivars may/will be invalid), and so you should never rely on a specific object state. These methods should only be used to continue deconstructing object state.

这是我们不鼓励在dealloc中使用属性设置器(setFoo:方法)的根本原因:可能将另一个对象注册为观察者,并且使用该属性将触发KVO通知,并且如果观察者希望对象具有有效状态,它们可能会失去运气,并且事情可能会迅速崩溃.

This is the fundamental reason why we're discouraged from using property setters (setFoo: methods) in dealloc: another object may be registered as an observer, and using the property will trigger a KVO notification, and if the observer is expect the object to have a valid state, they could be out of luck and things can blow up very quickly.

TL; DR:

是的,只要您对此有所了解,它就是安全的.

Yes, it's safe, as long as you're smart about it.

这篇关于在dealloc时在self上调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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