Nib Loading and Memory Management

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值