You use the following lifetime qualifiers for variables just like you would, say, const.
__strong
__weak
__unsafe_unretained
__autoreleasing
- __strong is the default. An object remains “alive” as long as there is a strong pointer to it.
- __weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.
- __unsafe_unretained specifies a reference that does not keep the referenced object alive and is not set to nil when there are no strong references to the object. If the object it references is deallocated, the pointer is left dangling.
- __autoreleasing is used to denote arguments that are passed by reference (id *) and are autoreleased on return.
You should decorate variables correctly. When using qualifiers in an object variable declaration, the correct format is:
ClassName * qualifier variableName;
for example:
MyClass * __weak myWeakReference;
MyClass * __unsafe_unretained myUnsafeReference;
Other variants are technically incorrect but are “forgiven” by the compiler. To understand the issue, see http://cdecl.org/.