Automatic Reference Counting in Objective-C
A document has appeared on the Clang website describing requirements for Automatic Reference Counting in Objective-C. This provides a service, akin to C++'s
auto, which allows objects to automatically take part in the
retain/release/autorelease cycle without requiring the user to do anything explicitly about it.
Objective-C uses a form of reference counting based on convention. Objects which are held on to are
retained, which increments their reference count. When an object is let go, the reference is
released instead. When the retain count goes to zero, the object is destroyed.
To allow for factory methods, which return a created instance but do not control its lifecycle, Objective-C has the concept of autorelease pools. These are stack-local lists of objects which, at the end of the processing loop (typically after processing an event from an event queue), the pool is drained, which reduces the reference count for any object in the list. If any reference counts drop to zero, then it is destroyed. On the other hand, if it has been
retained by other code in the loop's processing, it is kept alive for later use.
Objective-C has an informal naming convention for methods indicating their use. Objects such as
new return an object in which the caller is expected to take over ownership of the object. Methods with
with (such as
stringWithFormat) return an autoreleased object.
Objective-C 2.0 added a number of additions to the language, including blocks and properties, which have automatic retain and release syntax. But with the automatic reference counting, the compiler is now able to deduce (in a fairly small, but wide-ranging, number of cases) where to put appropriate
In addition, the automated insertion of these balanced
retain/release calls can be optimised away, if the compiler can prove the sequence of call actions between a pair of functions. To do this, certain classes of calls (such as
new are allocated into class families, which are new extensions that direct the compiler what to do. As a side-effect,
init methods which are not annotated are now flagged as warnings if they do not correspond to normal behaving init methods.
The new behaviour will be implemented in an upcoming release of Clang, and may be enabled with
-fobjc-arc. It is expected that devices with limited memory will use this instead of Objective-C garbage collection, which can be enabled with
-fobjc-gc on desktop platforms.
In the new C++ standard auto is used to declare variables with type inference.
I fail to see what it has to do with the Objective-C's reference counting.
Re: C++ auto?!
If in future I need to develop something in C++ I'll start to develop a simple reference counting facility similar to that of Objective-C. I think that is not complex to implement and the advantages are huge.
John Krewson, Steve Ropa and Matt Badgley Nov 24, 2014