ARC与非ARC下的Weak-Strong Dance
来源:互联网 发布:淘宝店铺怎么进货 编辑:程序博客网 时间:2024/05/29 13:12
ARC
在使用block过程中,经常会遇到retain cycle
的问题,例如:
- (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:_observer];}- (void)loadView{ [super loadView]; _observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"testKey" object:nil queue:nil usingBlock:^(NSNotification *note) { [self dismissModalViewControllerAnimated:YES]; }];}在block中用到了self,self会被block retain,而_observer会copy一份该block,就是说_observer间接持有self,同时当前的self也会retain _observer,最终导致self持有_observer,_observer持有self,形成
retain cycle
。对于在block中的retain cycle
,在2011 WWDC Session #322 (Objective-C Advancements in Depth)有一个解决方案weak-strong dance
,很漂亮的名字。其实现如下:
- (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:_observer];}- (void)loadView{ [super loadView]; __weak TestViewController *wself = self; _observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"testKey" object:nil queue:nil usingBlock:^(NSNotification *note) { TestViewController *sself = wself; [sself dismissModalViewControllerAnimated:YES]; }];}在block中使用self之前先用一个
__weak
变量引用self,导致block不会retain self,打破retain cycle,然后在block中使用wself之前先用__strong
类型变量引用wself,以确保使用过程中不会dealloc。简而言之就是推迟对self的retain,在使用时才进行retain。这有点像lazy loading的意思。注:iOS5以下没有__weak
,则需使用__unsafe_unretained
。
非ARC
在非ARC环境中,显然之前的使用的__weak
或__unsafe_unretained
将会是无效的,那么我们需使用另外一种方法来代替,这里就需要用到__block
。
__block
在ARC和非ARC中有点细微的差别(Automatic Reference Counting : Blocks):
- 在ARC中,
__block
会自动进行retain - 在非ARC中,
__block
不会自动进行retain
因此首先要注意的一点就是用__block
打破retain cycle
的方法仅在非ARC下有效,下面是非ARC的weak-strong dance
:
- (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:_observer]; [_observer release]; [super dealloc];}- (void)loadView{ [super loadView]; __block TestViewController *bself = self; _observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"testKey" object:nil queue:nil ngBlock:^(NSNotification *note) { [bself retain]; [bself dismissModalViewControllerAnimated:YES]; [bself release]; }];}
将self赋值为__block
类型变量,在非ARC中__block
类型变量不会进行retain,从而打破retain cycle,然后在使用bself前进行retain,以确保在使用过程中不会dealloc
- ARC与非ARC下的Weak-Strong Dance
- 非ARC(assign,retain,copy)与ARC(strong,weak)
- [郭襄跳崖]戏说arc下的weak和strong
- ARC Strong/Weak Variables
- iOS5 ARC strong weak
- ARC 中 Strong,Weak
- weak,strong --- ARC
- ARC 指南-weak strong
- ARC下IBOutlet用weak还是strong
- ARC下IBOutlet用weak还是strong
- iOS开发-ARC下weak strong使用
- iOS学习笔记——ARC两三事(strong、weak详解,ARC与非ARC混编)
- arc中strong和weak的区别
- ARC中strong、weak、unsafe_unretained的区别
- iOS5 strong, weak, unsafe_unretained ARC
- iOS arc机制 strong weak
- iOS ARC机制 weak strong
- iOS5 strong, weak, unsafe_unretained ARC
- IOS4的多任务机制概述
- JAVA程序员面试32问
- 十个经典排序算法总结版(1)前五个
- PKU 2318 叉积+二分
- C#中的is关键字原来会做null检查
- ARC与非ARC下的Weak-Strong Dance
- jQuery animate()方法详解、实例、扩展(详细版)
- 滑雪
- mini2440启动代码分析
- ABAP对话框
- oledb 连接Excel文件所对应的的多种连接方式
- 开发者必备的6款源码搜索引擎
- tablespace status
- NYOJ,139,我排第几个