iOS property strong/weak

来源:互联网 发布:网络小贷业务模式 编辑:程序博客网 时间:2024/06/02 05:23

最重要的放在前面,IBoutlet,官方以前推荐weak,现在推荐strong! 


先说按照weak,我们应该知道的原理:


如果使用StoryBoard托线,控件用weak

因为stroyboard中会有强引用对象,然后用_weak,不会出现直接释放的问题


如果用代码创建,控件用strong

直接用strong,强引用生成的对象.


然后,再看变化,根据stackOverflow上关于这个问题的提问,  Should IBOutlets be strong or weak under ARC?


现在这个提问的置顶回答明确提出,2015 WWDC上,推荐值为strong(更加说服力的是,回答问题的人,还在推特上联系了IB项目组的一个开发工程师,人家确认是strong)

下面就是置顶回答:

The current recommended best practice from Apple is for IBOutlets to be strong unless weak is specifically needed to avoid a retain cycle. As Johannes mentioned above, this was commented on in the "Implementing UI Designs in Interface Builder" session from WWDC 2015 where an Apple Engineer said:

And the last option I want to point out is the storage type, which can either be strong or weak. In general you should make your outlet strong, especially if you are connecting an outlet to a subview or to a constraint that's not always going to be retained by the view hierarchy. The only time you really need to make an outlet weak is if you have a custom view that references something back up the view hierarchy and in general that's not recommended.

I asked about this on Twitter to an engineer on the IB team and he confirmed that strong should be the default and that the developer docs are being updated.

https://twitter.com/_danielhall/status/620716996326350848https://twitter.com/_danielhall/status/620717252216623104

现在API文档关于IBoutlet的解释依然是weak,因为还没更新,说是将更新...

而这个提问最下方的另一个问答,更是直接指出了WWDC哪里说明了这一点,有兴趣的可以去看视频,(上面黄块的话,就是工程师的原话)

The evidence on their WWDC session is in session 407 - Implementing UI Designs in Interface Builder and starts at 32:30. 


至于从weak到strong的变化的原因,我的理解是

首先看一个变化:

- (void)viewDidUnload这个方法已经废弃了,从这个方法在API文档的discussion中了解到,在ios5以及前面:

In iOS 5 and earlier, when a low-memory condition occurred and the current view controller'€™s views were not needed, the system could opt to call this method after the view controller'€™s view had been released. This method was your chance to perform any final cleanup. If your view controller stored separate references to the view or its subviews, you could use this method to release those references. 

清除视图的时候,需要清引用,如果是强引用,就必须清,否则会影响到view的清理,也就应该会影响到nib上托的控件清理.

但是ios6以后:

In iOS 6 and later, clearing references to views and other objects in your view controller is unnecessary.

不需要清理了.为什么?我猜测,以前是只清nib不清控制器对象,所以,视图不加载的时候,要通过unload置nil.

而现在应该是nib,控制器对象都清.这样的话,直接把IBoutlet的父视图的控制器清了,父视图的所有者就没有了,完蛋,那么IBoutlet变量的所有者就没有了,完蛋,从上而下的清除. 

这样也就不会因为strong,影响到需要清除nib的时候,清除nib了.

而且,IB,对于nib的管理,也可以根据是否有变量strong引用,来合理清除暂时不用的nib了.

以上只是一种合理分析,因为这已经不是语法层的问题,这是实现层的问题,我们只能做出猜测.

用stackOverflow最后一名回答者的话(他也提出一种关于nib的解释,但我没看懂....)

Still it would be nice to get a deeper explanation from Apple.


0 0