Is it a legitimate practice to rely on a deterministic dealloc (ex: for clean-up)?
Since ARC, and even manual reference counting, is inherently deterministic, I was wondering what other people thought about relying on dealloc getting called immediately (relatively, considering autoreleasepool).
In other modern programming languages, like C#, a dispose-like pattern is employed when you need deterministic clean-up. And I would imagine Obj-C with garbage collection encourages this behavior, as well.
So, with that said, an example would be a UIViewController which cancels outstanding operations in dealloc, rather than trying to program around the sometimes frustrating semantics of viewDidDisappear.
Another example would be a stream object that implicitly opens and closes in init and dealloc, respectively, rather than requiring open or close to be called.
Since Apple has deprecated GC, I would imagine that these sorts of patterns won’t be broken anytime soon, and they are incredibly handy, though I can’t find any documentation on whether this should be encouraged.
You are absolutely correct, you can rely on
deallocbeing called relatively soon after the last reference is released (manually or though ARC, it does not matter). Unlike GC where the finalizer is called when the system has some free time, or in some cases is never called,deallocgets called very reliably. Apple allows and even encourages using this pattern by suggesting that we should perform all of our resource clean-up tasks insidedealloc.This does not mean, however, that you should rely on
deallocexclusively. For example, take a look at theNSStreamclass: it offers you an explicitclosemethod, letting you force closing the stream at will, without waiting for the call ofdeallocto happen. This is a very good pattern to follow in case the resource is very expensive (file handles, semaphores, etc.): the primary mechanism for releasing these resources should be a separateclosemethod. Thedeallocmethod should release the resource as well, but it should also issue a warning, informing your that you missed a call ofclose.