Calling a method on self while in dealloc

前端 未结 1 520
一个人的身影
一个人的身影 2020-12-20 17:19

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 dictiona

相关标签:
1条回答
  • 2020-12-20 18:09

    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.

    0 讨论(0)
提交回复
热议问题