I have ‘come of age’ in the ARC era. Although I have done some manual reference counting and think I understand it, I took a test on my Obj-C skills lately and ran across this puzzle. My answer was the simple, obvious and incorrect choice.

To understand it better I created this test project and picked it apart. Try the puzzle yourself and then read my thoughts below. If you see any errors in my logic, please let me know!

The Code

The Choices

The initial mistake I made was not thinking about when the blocks would be executed. Because dispatch_async() was putting the block on the main queue, I read this code as a straight procedural list of commands, and came up with answer #2. This was completely wrong. I even missed the first clue that the order of the 4 logged lines was just as important as the retain count being printed.

After creating the test project and seeing for myself what the correct answer was I was flumexed. But, quickly I reminded myself that dispatching a block, even on the same queue, will delay the execution of that code until the next run loop. The 2nd nested block doesn’t even capture object (increasing the retain count) until after the first executed NSLog prints out the retain count for ‘D’.

With the answer #4 clearly true, I could now re-read the code to understand it. I added comments with my thoughts:

Go top