原文来自这里

今天用Xcode5的时候,发现默认的IBoutlet的属性设置为weak——因为Xcode5建立的工程都是ARC的了。但是当时还有点不明白,因为项目的原因,一直没有正式使用过ARC。于是,为了搞清楚为什么,google了一下,有很多答案。试着从Apple文档寻找线索,在这里找到了说明:

From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create should therefore typically be weak, because:

  • Outlets that you create to subviews of a view controller’s view or a window controller’s window, for example, are arbitrary references between objects that do not imply ownership.
  • The strong outlets are frequently specified by framework classes (for example, UIViewController’s view outlet, or NSWindowController’swindow outlet).

简单的说,如果IBOutlet对象是nib/sb scene的拥有者(File’s owner)所持有的对象,那么很显然拥有者必须“拥有”对象的指针,因此属性应设置为strong。而其他的IBOutlet对象的属性需要设置为weak,因为拥有者并不需要“拥有”他们的指针。举例来说,UIViewController的view属性是strong,因为controller要直接拥有view。而添加到view上的subviews,作为IBOutlet只需要设置为weak就可以了,因为他们不是controller直接拥有的。直接拥有subviews的是controller的view,ARC会帮助管理内存。

紧接着,文档里又提到:

Outlets should be changed to strong when the outlet should be considered to own the referenced object:

  • As indicated previously, this is often the case with File’s Owner—top level objects in a nib file are frequently considered to be owned by the File’s Owner.
  • You may in some situations need an object from a nib file to exist outside of its original container. For example, you might have an outlet for a view that can be temporarily removed from its initial view hierarchy and must therefore be maintained independently.

第一种情形前面已经解释过了,对于第二种,通俗点将,就是controller需要直接控制某一个subview并且将subview添加到其他的view tree上去。

单纯从ARC的角度思考,用weak也是很显然的:因为subview添加到view上时,view会“拥有”subview。当然,给IBOutlet属性设置为strong也没有错,“纠结谁对谁错“的问题可能需要上升到模式或者编码习惯的问题,已经超出本文的范围。

最后附上stakoverflow上的答案:

http://stackoverflow.com/questions/7678469/should-iboutlets-be-strong-or-weak-under-arc/7729141#7729141

除了选中的答案之外,其他人的回答也非常有意思,大家可以看看。

最新文章

  1. iOS中空字符串报错
  2. WEBAPP开发技巧(手机网站开发注意事项)
  3. 介绍开源的.net通信框架NetworkComms框架 源码分析(二十一 )TCPConnectionListener
  4. awk 匹配不是 pattern 的内容
  5. rubycas-client单点登录
  6. Java开发中程序和代码性能优化
  7. Unicode和多字节字符集 (MBCS) 杂谈
  8. Hibernate——property的access属性
  9. 约束优化方法之拉格朗日乘子法与KKT条件
  10. log4j和web.xml配置webAppRootKey 的问题
  11. 【原】Storm 消息处理保障机制
  12. Play Framework Web开发教程(33): 结构化页面-组合使用模板
  13. NFinal 揭秘之控制器
  14. Easy sssp
  15. linux系统性能监控--内存利用率
  16. 项目管理——WBS工作分解法
  17. C#使用xpath简单爬取网站的内容
  18. [js]设计模式小结&对原型的修改
  19. centos 7 安装sql 审核工具 inception + archer
  20. Spring boot变量的初始化顺序

热门文章

  1. 软件项目技术点(1)——d3.interpolateZoom-在两个点之间平滑地缩放平移
  2. Office - InfoPath
  3. 阿里云更懂你的数据库,免费提供DBA服务
  4. 关于pom版本提交不成功的问题
  5. Visio中锁定元件
  6. 如何让LoadRunner实现多个场景运行?
  7. 【转】[C++]实现委托模型
  8. python UI自动化实战记录七:页面2用例编写
  9. 字符串拼接+和concat的区别
  10. CAShapeLayer使用