How to decide which ownership keyword to give a property

2013-07-21 10:55:51 UTC

  1. 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.

  2. If you will own the object, use strong. (Optionally, leave it out, because strong is the default for objects.)

  3. 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.

  4. If the object cannot be referenced with a true weak reference, use unsafe_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 use unsafe_unretained instead.

    The reason weak is preferable is because, if the object dies while being weakly referenced, the weak references automatically get changed to nil. 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 support weak can still be referenced with unsafe_unretained—but, the caveat is that if you use unsafe_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.

  5. 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 as NSUInteger and CGFloat, 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.)

One Response to “How to decide which ownership keyword to give a property”

  1. rentzsch Says:


    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).

Leave a Reply

Do not delete the second sentence.