In particular, would this kind of code always work as intended (where MyResourceGuard is an object that locks an exclusive resource in its init method and frees the lock in its dealloc method):
NSLog(@"About to capture some exclusive resource.");
{
MyResourceGuard* guard = [MyResourceGuard new];
// Do something with the exclusive resource here.
}
// guard is out of scope, therefore its dealloc should have
// been called right away and the resource should already
// be free again at this point.
I have read in books and blogs that in contrast to e.g. Java garbage collection, ARC destroys objects as soon as the reference count decreases to zero (and not at some time of its own convenience), but I haven’t read this in any official documentation by Apple. And if that were true, why would we ever need the new @autoreleasepool keyword introduced with ARC?
From debugging, I have always seen the object dealloc’ed immediately, except when an exception is raised in a try-catch-block, in which case dealloc actually was never called (is that a Mac bug, or just one of these scary Objective C oddities?).
No. You don’t have deterministic scope based destruction of ObjC objects as your example shows.
For example, this program could result in deadlock:
The best you can do if you need this functionality is to use C++ types (SBRM, RAII) — also available in Objective-C++ (but not applicable to objc objects).
It comes close, but you just have to wait until the reference count reaches zero for
-deallocto be called, and that’s why the guarantees are off (usually != always). This problem is actually quite similar to why you would never rely on or use-retainCount(where it is available). Examples: Autorelease Pools, exceptions, changes to the runtime or ARC generated code, compiler optimizations, using implementations which have different code generation flags could result in the life of the objc object being prolonged beyond the scope.Update
The whole page on ARC at clang’s site is a good read on the subject — including details, guarantees (and lack of guarantees), but in particular:
Even if you do use the
objc_precise_lifetimeattribute, it will apply to reference count operations for that strong local variable — not the lifetime of the object.