您的位置:首页 > 其它

Nib Loading and Memory Management

2013-11-09 00:01 274 查看
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 that
you 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.)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: