Calling the self method located in dealloc

I have a dictionary of objects that need to be cleaned before they are released. I have a method that does this for the entire dictionary. Before releasing the dictionary in my -dealloc method, I want to do the same. However, I am not sure about the state of the object at the time of release. For example, in C # or Java, I would never call a method for an object that has been finalized, but I'm not sure if this applies to Objective-C and release. Is it permissible to call the cleanup method on self at release time, or should I duplicate this function in -dealloc ?

+7
source share
1 answer

Yes, you can call methods from your dealloc method, although it is wise to be careful. To a large extent, the only methods you should call should be tear-down methods or methods that help clean up the object before its resources are recovered. Some of these cleaning methods include:

  • unregistration for notifications through the notification center
  • removing yourself as an observer with key values
  • other common cleaning methods

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

This is the main reason why we are not recommended to use property definition tools ( setFoo: methods in dealloc : another object can be registered as an observer, and using this property will trigger a KVO notification, and if the observer expects the object to have the correct state, it maybe unlucky and everything can explode very quickly.

TL; DR:

Yes, it is safe if you are smart.

+10
source

All Articles