When should I use the weak or strong qualifier wit

2019-03-11 19:07发布

问题:

Possible Duplicate:
Should IBOutlets be strong or weak under ARC?

In the documentation, I read "Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong."

Examples? I don't understand when it's better use "weak" instead of "strong" property for an IBOutlet.

回答1:

In general: if you are making an outlet to a subview of the ViewControllers subview it should be weak. The object exists as long as the top view exists (between viewDidLoad and viewDidUnload). As iOS 5 ARC automatically nullifies weak links, when the viewController unloads its view and view hierarchy is destroyed, your outlet is automatically set to nil.

But maybe you want to create another object in your nib file (a model object). As this object is not under the view hierarchy, you need to make the iboutlet strong. If you make it weak linked, the object will be autoreleased since no other object has a strong reference to it and ARC will release it and set nil to your IBOutlet. This is not the case of a subview since its superview mantains a strong link with it.