Calling a method on self while in dealloc
Asked Answered
L

1

7

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?

Leicestershire answered 23/2, 2011 at 17:36 Comment(0)
M
11

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.

Mejia answered 23/2, 2011 at 17:49 Comment(5)
Nice, thanks Dave. That's exactly what I wanted to call: a tear-down method with no side effects. But I am nervous about potential future refactoring adding responsibility to that method. I can guarantee I know what it's doing now, but sometimes future me can be dumb. Maybe I just talked myself out of it.Leicestershire
@Don: A tear-down method is perfectly fine, especially if it helps further the DRY principle.Mejia
would it be advisable to call a method that closes a database connection or deletes temporary files in -dealloc or is there a more appropriate place for such things?Fredkin
@Fredkin that seems like a reasonable thing to do in deallocMejia
Database connections etc. should have been closed down earlier, because there is no guarantee when exactly dealloc is going to be called. There isn't even a guarantee that dealloc is called at all (if you quit an application, all the objects just disappear without dealloc being called).Horton

© 2022 - 2024 — McMap. All rights reserved.