xib storyBoard IBOutlet连出来的视图属性为什么可以被设置成weak

来源:互联网 发布:python取消注释快捷键 编辑:程序博客网 时间:2024/06/06 05:30

答案在前

使用storyboard创建的viewController,那么会有一个叫 _topLevelObjectsToKeepAliveFromStoryboard的私有数组强引用所有top level的对象,同时top level对象强引用所有子对象,那么vc没必要再强引用top level对象的子对象。

好吧!我最初看完之后没理解什么意思,然后查看了stackoverflow和apple doc,把思路阐述一下,如有理解的错误希望指正。

构建过程

什么是top level对象?apple doc给出的答案如下

The top-level objects are the subset of these objects that do not have a parent object.
The top-level objects typically include only the windows, menubars, and custom controller objects that you add to the nib file. (Objects such as File’s Owner, First Responder, and Application are placeholder objects and not considered top-level objects.)

那么我们在Storyboard创建一个控件的引用关系是怎样的呢?

以UIButton为例:UIViewController->UIView->UIButton

如果我们在vc中这样写

他们之间的引用关系用图表示如下:

Paste_Image.png

viewController强引用view对象,同时view强引用button对象,那么你声明属性的时候使用weak就可以了。(觉得Strong也可以,但是完全没必要)

每次我们在SB上创建子控件的时候,我们其实都将它加到view tree上,它的parrent view拥有它的强引用。

释放过程呢

那么内存释放过程是怎样的呢?其实不管声明的属性是强引用还是弱引用,在控制器消失的时候,这个属性消失,View消失,subViews消失,控件也就消失了。

Paste_Image.png


阅读全文
0 0
原创粉丝点击