Nib Loading and Memory Management

来源:互联网 发布:怎么在淘宝天猫开店 编辑:程序博客网 时间:2024/06/12 00:21

On iOS, when a nib loads, the top-level nib objects that it instantiates are autoreleased. So if someone doesn’t retain them, they’ll soon vanish in a puff of smoke. There are two primary strategies for preventing that from happening:

Retain the top-level objects

When a nib is loaded by calling NSBundle’s loadNibNamed:owner:options: or UINib’s instantiateWithOwner:options: (Chapter 7), an NSArray is returned consisting of the top-level objects instantiated by the nib-loading mechanism. So it’s sufficient to retain this NSArray, or the objects in it.

For example, when a view controller is automatically instantiated from a storyboard, it is actually loaded from a nib with just one top-level object — the view controller. So the view controller ends up as the sole element of the array returned from instantiateWithOwner:options:. The view controller is then retained by the runtime, by assigning it a place in the view controller hierarchy; for instance, in an app with a main storyboard, UIApplicationMain instantiates the initial view controller from its nib and assigns it to the window’s rootViewController property, which retains it.

Object graph

If an object instantiated from a nib is the destination of an outlet, the object at the source of that outlet may retain it — typically through an accessor. Thus a chain of outlets can retain multiple objects (Figure 12-2). For example, when a view controller automatically loads its main view from a nib, its proxy in the nib has a view outlet to the top-level UIView in that nib — and UIViewController’s setView: retains its parameter.

Moreover, a view retains its subviews, so all the subviews of that main view (and their subviews, and so on) are retained as well. (For this reason, an IBOutlet instance or property thatyou create in your own view controllers will usually be marked as __weak. It doesn’t have to be, but there’s usually no need for it to be __strong, because the destination interface object in the nib is already going to be retained through its place in the object graph.)

原创粉丝点击