To help better understand Automatic Reference Counting (ARC) I thought I’d write a collection of routines that highlight what happens in various different situations. I am taking advantage of the fact that a weak pointer becomes nil when the object it points to is deallocated.

The rule that the compiler is keeping to is to make sure that any object that is pointed to by a strong pointer will not be deallocated, and once the object no longer has any strong pointers pointing to it, it will be deallocated soon after. How this is achieved is an implementation detail and many of the routines below highlight different aspects of how the implementation is achieved. As such you should never rely on any object not being deallocated because you believe it will not be deallocated because it is still retained within an autoreleasepool as is demonstrated in the following code. This is important because how the goal is achieved of keeping an object alive over return boundaries is an implementation detail and the implementation can change in the future. For blocks the behaviour will be unreliable as you don’t what is between your code implementing the blocks and where the block gets called, there could for instance be one or more autoreleasepools.

One of the main things I got out of doing this is a better understanding of why I need to use autoreleasepools.

Can you work out what the last NSLog line for each routine will output? The answers are at the end.

One thing to note before reading the code and trying to determine what the output is, is that passing a weak pointer to a function (NSLog for example) will result in the object pointed to by the weak pointer being retained and put into the autoreleasepool. Also if “%@” gets a nil string it will output “(null)”.

Read the rest of this entry »

Tags: , ,