IBOutlet 为什么默认是weak的

IBOutlet 为什么默认是weak的 文档阅读笔记
标签: iOS
[TOC]

IBOutlet为什么使用weak

前言

无聊间提了个问题,为什么IBOutlet 默认是weak的.才发现,回答千奇百怪。
比如:1:viewCtroller 加载出来的时候,有可能属性还没有加载出来,所以使用weak。2:weak初始化失败了在viewcontroller 中调用也是可以的,只是不显示而已。
……什么鬼。。。偶然听到一同事说,如今是面向google写代码了,所以基础都不重要了,重要是会google 最差的也是会百度!!!晕

通过查看 官方文档。其实也不是不能使用strong 而是使用strong不符合strong weak 的使用原则。囧!!重点就是下面这一段!

Each time you ask the NSBundle or NSNib class to load a nib file, the underlying code creates a new copy of the objects in that file and returns them to you. (The nib-loading code does not recycle nib file objects from a previous load attempt.) You need to ensure that you maintain the new object graph as long as necessary, and disown it when you are finished with it. You typically need strong references to top-level objects to ensure that they are not deallocated; you don’t need strong references to objects lower down in the graph because they’re owned by their parents, and you should minimize the risk of creating strong reference cycles.

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’s window outlet).
@property (weak) IBOutlet MyView *viewContainerSubview;
@property (strong) IBOutlet MyOtherClass *topLevelObject;

一般的IBOutlet直接关联到viewcontroller。但是跟其关联的控件并不是添加在controller上,而是添加到controller的view上,比如[self.view addSubView:xxx]; 这个时候self.view已经对xxx 强引用过了,self.view才是持有xxx的对象。这样子才符合引用计数的规则。所以直接IBOutlet顶级view的时候肯定是strong的。

如何使用Nib or SB(StoryBoard)

这还用说,网上一大堆,面上google编程去吧哈哈哈

如何改成strong

直接改成strong 啊。没什么不可以,手工写代码,不也经常在viewcontroller里创建一个view然后添加到self.view上么……
当然,IBOutlet顶级view的时候肯定是strong的。因为要持有。

weak strong 区别

Objective-C高级编程 iOS与OS X多线程和内存管理里面讲的比较详细。
strongweak的区别:strong表示对对对象的强引用,在改变量被废弃的时候,会释放被赋予的对象。
weak不持有对象,在对象超出作用范围时候,对象被释放。跑题了,google上有很多,不过还是建议看一下那本书!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值