ViewController中的UIView Property要设置为weak还是strong
2016-04-11 17:06
507 查看
ViewController中的UIView Property要设置为weak还是strong
众所周知,从IB中拖出来的outlet Xcode会默认设置为weak,那么代码new出来并且addSubview到self.view的view,我们在property里要设置为strong还是weak呢。
Weak or Strong?
假设一个ViewController的self.view中有一个Label,那么他们三者的关系是:![](http://codingtime.me/images/post/subview_weak_map.png)
可以看到Label的所有者其实是self.view,正常来说一个对象只有一个所有者,如果再将ViewController中的Label引用声明为strong,那么当label从self.view中移除后,label将不会销毁,造成View的冗余。
于是我们愉快地把Label声明为
weak,但是在初始化label的时候,Xcode又猝不及防地扔给我们一个warning。
![](http://codingtime.me/images/post/subview_weak_code.png)
咦,我们
addSubview之后
self.label不是已经被
self.view强引用了嘛,这又是什么鬼为什么Xcode还跟我们说都是weak惹的祸这个对象马上就要被释放了。编译一下试试,发现ViewController里面果然一片雪白,完全没有刚刚加进去的label的影子,看来Xcode没有骗我们。
Label消失的原因
我们来逐步分析一下这几句话背后引用计数的变化:self.label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
这句话其实应该拆成两句话,首先alloc出了一个
UILabel的临时变量,然后再使用
setLabel将临时变量复制给self.label。其中引用计数变化如下
id temp = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; //tempLabel引用计数为1 [self setLabel: temp]; //由于self.label是weak,因此此处引用计数还是1
然后接下来的代码中没有再用到temp,temp被释放,此时引用计数为0,temp被设为nil,于是self.label也被设为nil
[temp release]; //引用计数变为0
最后
addSubview时只add了一个nil的view,引用计数并不能增加,所以我们在运行时才没有看到new出来的label。
[self.view addSubview:self.label]; //此处等于[self.view addSubview:nil];
正确的打开方式
正确的打开方式是先用一个临时变量把init出来的变量hold住,防止temp在执行的过程中被释放,先亮代码:
UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; self.label = tempLabel; self.label = @"Hello World"; [self.view addSubview:self.label];
这段话的引用计数过程是
UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
这句话可以拆成两句
id temp = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; //temp引用计数为1 UILabel *tempLabel = temp; //局部变量默认是strong,temp引用计数增至2
self.label = tempLabel; //self.label是weak,不改变引用计数 self.label = @"Hello World"; [self.view addSubview:self.label]; //引用计数+1,temp的引用计数为3 //这段代码执行完后,临时变量将被释放 [tempLabel release]; //temp引用计数为2 [temp release]; //temp引用计数为1
整段话执行完后,既保证了
temp在执行过程中过早释放,又保证了在执行完后
temp的引用计数为1,因此是初始化
UIView的property较为科学的方法。
本文参考了以下内容:
Best practice for custom UIView subview strong vs weak
Differences between strong and weak in Objective-C
Creating views programmatically Strong Vs Weak subviews in controller
Why is addSubview: not retaining the view?
相关文章推荐
- ${pageContext.request.contextPath} JSP取得绝对路径
- 列标头固定的联系人列表
- Java 实例 - 队列(Queue)用法
- 常用的easyui使用方法
- 用MSBuild和Jenkins搭建持续集成环境(2)
- [转] form.getForm().submit的用法及Ext.Ajax.request的小小区别
- 用MSBuild和Jenkins搭建持续集成环境(1)
- iOS开发基础学习笔记——标签栏(UITabBar)
- UILabel 添加下划线,改变字体颜色,NSMutableAttributedString实现富文本
- caffe Data layer prefetch queue empty重启
- SQL GUID去除横线,并转换为小写
- Hibernate-Criteria Queries
- 更新UI操作,Handler与runOnUiThread
- Java优先队列(PriorityQueue)示例
- iOS UICollectionView实现图片轮播 —— HERO博客
- VC生成GUID
- 如果需要将UIView的4个角全部都为圆角,做法相当简单,只需设置其Layer的cornerRadius属性即可
- 在海思hi3520上移植minigui3.0
- Spark Streaming + Flume Integration Guide
- iosUILabel高度自适应