All posts tagged “reference”

When to use weak or strong

One unfortunate consequence (if you want to call it that) of ARC is the ambiguity of when a IBOutlet@property should be declared as weak or strong. The ambiguity arises from the fact that most outlets have no discernible behavioral differences between weak or strong—it just works.

…except when it doesn’t… and things crash, or the compiler warns about weak or strong use.

So what should one do? Always declare IBOutlet properties as weak, except when they need to be strong, as explained by Apple in their Resource Programming Guide section on Nib Files:

Outlets should be changed to strong when the outlet should be considered to own the referenced object:

  • This is often the case with File’s Owner—top level objects in a nib file are frequently considered to be owned by the File’s Owner.

  • You may in some situations need an object from a nib file to exist outside of its original container. For example, you might have an outlet for a view that can be temporarily removed from its initial view hierarchy and must therefore be maintained independently.

The reason why most IBOutlet views can get away with weak ownership is that they are already owned within their respective view hierarchy, by their superview. This chain of ownership eventually works its way up to the view owned by the view controller itself. Spurious use of strong ownership on a view outlet has the potential to create a retain cycle.