Calling a method on self while in dealloc

拈花ヽ惹草 提交于 2019-12-29 08:35:10

问题


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?


回答1:


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:

  • unregistering for notifications via a notification center
  • removing yourself as a key-value observer
  • other general cleanup methods

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.

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.



来源:https://stackoverflow.com/questions/5094615/calling-a-method-on-self-while-in-dealloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!