How to decide which ownership keyword to give a property
-
If the object may come in a mutable variant (like NSString has NSMutableString), use
copy
, so that you don’t end up holding a mutable object that somebody mutates while you’re holding it. -
If you will own the object, use
strong
. (Optionally, leave it out, becausestrong
is the default for objects.) -
If the object will own you, use
weak
. For example, a table view weakly references its data source and delegate, because they are very often the VC or WC that indirectly owns the table view. -
If the object cannot be referenced with a true
weak
reference, useunsafe_unretained
. A select few classes*, such as NSTextView, do not support weak references. You will get an exception at run time if you try to establish a weak reference to such an object. You will have to useunsafe_unretained
instead.The reason
weak
is preferable is because, if the object dies while being weakly referenced, the weak references automatically get changed tonil
. That’s also the part that certain classes are allergic to.unsafe_unretained
doesn’t have this feature, which is why the classes that don’t supportweak
can still be referenced withunsafe_unretained
—but, the caveat is that if you useunsafe_unretained
, you must ensure that the object will never get deallocated while you are weakly holding it—i.e., that you let go of your unsafe unretained reference before the last owner of the object lets go of that ownership. - Never use
assign
. For objects,unsafe_unretained
is synonymous and clearer (it explicitly says that it is unsafe, which it is). For non-objects (such asNSUInteger
andCGFloat
, leave it out—assign
is the default for such values.
* The Transitioning to ARC FAQ includes a complete list of classes that do not support weak references. ↶
(This is an expanded version of a comment I posted on Stack Overflow.)
July 21st, 2013 at 21:57:38
Interesting.
I basically agree, but I do leave in strong and assign even when default mostly for visual formatting reasons — I find it easier to scan properties that all have two words (the ubiquitous nonatomic (which I put first since then it’s constant-length noise I can visually discard) and then the meaningful keyword).