论iOS中使用UI控件时,修饰符用strong?还是weak好呢
2018-03-13 本文已影响89人
长风留言
iOS中使用UI控件时,修饰符用strong?还是weak好呢?
大部分iOS工程师一般写代码的时候,都会使用strong,这是为了方便、快捷、不易报错,有的时候如果写成weak,会莫名其妙的报错,比如崩溃,但是看代码却没有问题。当然细心的工程师其实在使用Xcode的时候,在一个地方会发现,系统所使用的UI控件修饰符全是weak,当你用xib、view等拖控件关联时,这个时候系统提供的修饰符全部是weak,所以,其实官方推荐在实际开发中尽量用weak,那么怎么验证呢,我们可以通过一个示例程序来进行说明。
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) UIView *strongView;
@property (nonatomic,strong) UIView *selfStrongView;
@property (nonatomic,weak) UIView *weakView;
@property (nonatomic,weak) UIView *selfWeakView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1、创建selfStrongView
self.selfStrongView = [[UIView alloc]initWithFrame:CGRectMake(50, 25, 50, 50)];
printf("self.selfStrongViewretain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(self.selfStrongView)));
[self.view addSubview:self.selfStrongView];
printf("self.selfStrongView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(self.selfStrongView)));
_strongView = [[UIView alloc]initWithFrame:CGRectMake(150, 100, 50, 50)];
printf("_strongView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_strongView)));
[self.view addSubview:self.strongView];
printf("_strongView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_strongView)));
UIView *selfView = [[UIView alloc]initWithFrame:CGRectMake(250, 150, 50, 50)];
self.selfWeakView = selfView;
printf("self.selfWeakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(self.selfWeakView)));
[self.view addSubview:self.selfWeakView];
printf("self.selfWeakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(self.selfWeakView)));
UIView *weaksView = [[UIView alloc]initWithFrame:CGRectMake(300, 200, 50, 50)];
printf("weakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(weaksView)));
_weakView = weaksView;
printf("_weakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_weakView)));
[self.view addSubview:_weakView];
printf("_weakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_weakView)));
}
- (void)viewWillAppear:(BOOL)animated
{
printf("self.selfStrongView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_strongView)));
printf("_strongView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_strongView)));
printf("self.selfWeakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(self.selfWeakView)));
printf("_weakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_weakView)));
}
@end
总结
在现在开发中,一般都是在ARC中,对于ARC来说,对象释放的最终根据还是根据引用计数为0时去释放。而weak与strong的根本区别是在set方法中,weak的set方法和strong的set方法都是释放旧值保留新值,但是weak的set方法会对其autorelease,即延迟release一次,而strong的set方法也是释放旧值保留新值,但是其不会延迟release。最终效果是strong会+1,weak不会+1.
要注意,用去赋值的时候是不调用set方法的,也就是说无论weak还是strong,只要用赋值都不会对引用计数加1,区别在于self.语法会调用set方法,strong的self.会调用set方法+1.而weak的_和self.语法都不会+1.
所以,建议用weak,用weak时无论用_和.语法都不会导致+1。用strong时用self.语法会导致+1.建议用weak。同时weak在对象回收以后可以将对象指针置成nil。