Experiments · A Lovely Computer · Chapter 9
The lock and its counter
Reference counting in Objective-C: leaks and crashes
Theme
Try itThe lock and its counter
Everything is computed in your browser; nothing is sent anywhere.
About this experiment
Before 2011 every Objective-C programmer on the Mac or the iPhone kept the count of owners in the head. A forgotten release left an object in memory for good, an extra one destroyed an object still in use.
The code starts like the author’s file: a lock made into a local variable and never handed over. Step through one opening and watch the counter, or open the program a hundred times. With ARC the compiler places the messages, but it cannot know that you meant to give the lock to the device.
From the book
A Lovely Computer · Chapter 9
retain/release
It worked only at the second attempt. At the developers’ conference in June 2011, three months after my lock, they showed ARC, automatic reference counting. The rules of ownership stayed as they were, but the retain and release calls were now placed by the compiler, which reads the program and, unlike a human being, does not lose count. On the fifteenth of June Chris Lattner told a mailing list that the code of this machinery had been made public, and Xcode 4.2 acquired a menu item that converted an existing project to the new order.
My project did not live to see that menu item. I last touched it in July 2011, and the lock in it is leaking to this day.