目錄
1. 概述
之前有寫過一篇博文: Block
但當時沒有具體討論何時該使用weakSelf, 何時又該使用strongSelf. 我們現在就從多個常用場景中來討論, 如何使用self的強弱引用來避免block的循環引用問題.
衆所周知, 由於對象之間循環強引用, 導致對象在作用域完了之後無法釋放, 最終造成內存泄露.
強引用會使引用計數加1, 而弱引用不會.
所以, 我們只需要在構成循環強引用的block中使用weakSelf, 而不是隻要碰到block就拼命weakSelf/strongSelf.
本文主要從應用和舉例論證出發, 不深入探討原理. 因爲相關原理方面的書籍文章比較晦澀難懂, 看完也不一定知道怎麼用.
2. 自定義block
demo搭建: 新建工程, 引入一個navigationController (便於VC返回), 再新建兩個VC: VC2和VC3.
VC2和VC3裏面分別實現以下方法:
- (void)dealloc
{
NSLog(@"%s", __func__);
}
- (void)callBlock:(void (^)(void))block {
if (block) block();
}
- (void)doSomething {
NSLog(@"%s", __func__);
}
VC中加載VC2, 目的是驗證點擊返回時看VC2是否能釋放.
viewController.m
#import "ViewController2.h"
- (void)viewDidLoad {
[super viewDidLoad];
ViewController2 *vc2 = [[ViewController2 alloc] init];
[self.navigationController showViewController:vc2 sender:nil];
}
然後在VC2中分四種情況來討論block的循環引用問題.
viewController2.m
#import "ViewController3.h"
@property (nonatomic, strong) ViewController3 *vc3;
- (void)viewDidLoad {
[super viewDidLoad];
// 情況一 (無泄漏)
ViewController3 *vc3 = [[ViewController3 alloc] init];
[vc3 callBlock:^{
[self doSomething];
}];
// 情況二 (無泄漏)
ViewController3 *vc3 = [[ViewController3 alloc] init];
vc3.myBlock = ^{
[self doSomething];
};
vc3.myBlock();
// 情況三 (無泄漏)
self.vc3 = [[ViewController3 alloc] init];
[self.vc3 callBlock:^{
[self doSomething];
}];
// 情況四 (有泄漏, 拋出警告)
self.vc3 = [[ViewController3 alloc] init];
self.vc3.myBlock = ^{
[self doSomething];
};
self.vc3.myBlock();
}
viewController3.h
@interface ViewController3 : UIViewController
typedef void (^MyBlock)(void);
@property (nonatomic, copy) MyBlock myBlock;
- (void)callBlock:(void (^)(void))block;
@end
下面來分析這四種情況, 爲方便說明, 我們將弱引用標記爲- ->, 將強引用標記爲—>.
2.1 情況一
VC2 --> VC3 --> block —> VC2(self).
無內存泄漏.
因爲VC3是局部變量, VC2沒有強持有它. 又因爲block是作爲方法的形參, 故VC3也不是強引用block.
點擊VC2的返回按鈕, log如下:
-[ViewController2 doSomething]
-[ViewController3 dealloc]
-[ViewController2 dealloc]
2.2 情況二
VC2 --> VC3 —> block —> VC2(self).
無內存泄漏.
雖然VC3強持有了block, 但VC2並沒有強持有VC3, 所以也不構成循環強引用.
點擊VC2的返回按鈕, log如下:
-[ViewController2 doSomething]
-[ViewController3 dealloc]
-[ViewController2 dealloc]
2.3 情況三
VC2 —> VC3 --> block —> VC2(self).
無內存泄漏.
block是作爲方法的形參, 故VC3也不是強引用block.
點擊VC2的返回按鈕, log如下:
-[ViewController2 doSomething]
-[ViewController3 dealloc]
-[ViewController2 dealloc]
2.4情況四
VC2 —> VC3 —> block —> VC2(self).
有內存泄漏.
點擊VC2的返回按鈕, 沒有釋放VC2和VC3. log如下:
-[ViewController2 doSomething]
且系統拋出警告:
3. 系統block
3.1 GCD
viewController2.m
@property (nonatomic, strong) dispatch_queue_t myQueue;
- (void)viewDidLoad {
[super viewDidLoad];
self.myQueue = dispatch_queue_create("com.KKBlockDemo.testQueue", DISPATCH_QUEUE_SERIAL);
dispatch_async(self.myQueue, ^{
[self doSomething];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateUI];
});
});
}
self —> self.myQueue --> self.
由於block是作爲dispatch_async的形參, GCD並不強持有block, 所以不會造成循環強引用.
同理, dispatch_get_main_queue中也沒有強持有block, 故也不會造成循環引用.
點擊VC2的返回按鈕, log如下:
-[ViewController2 doSomething]
-[ViewController2 updateUI]
-[ViewController2 dealloc]
3.2 UIView
viewController2.m
- (void)viewDidLoad {
[super viewDidLoad];
[UIView animateWithDuration:1.0
animations:^{
[self doSomething];
}
completion:^(BOOL finished) {
[self doSomething];
}];
}
類似GCD, UIView也沒有強引用block, 故不會造成循環引用.
點擊VC2的返回按鈕, log如下:
-[ViewController2 doSomething]
-[ViewController2 doSomething]
-[ViewController2 dealloc]
3.3 網絡請求
viewController2.m
- (void)viewDidLoad {
[super viewDidLoad];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
[self doSomething];
NSLog(@"data:%@", data);
}];
[task resume];
}
同樣, 以上例子也不會引起內存泄露.
點擊VC2的返回按鈕, log如下:
-[ViewController2 doSomething]
data:{length = 2443, bytes = 0x3c21444f 43545950 45206874 6d6c3e0d ... 2f68746d 6c3e0d0a }
-[ViewController2 dealloc]
4. 何時使用 weakSelf & strongSelf ?
在自定義block章節的情況四中, 我們需要引入弱引用weakSelf來打破循環強引用:
VC2 —> VC3 —> block --> VC2(weakSelf).
// 情況四
self.vc3 = [[ViewController3 alloc] init];
__weak typeof(self) weakSelf = self;
self.vc3.myBlock = ^{
[weakSelf doSomething];
};
self.vc3.myBlock();
同時, 在block中使用weakSelf還有另一個作用: 在block回調前, self可以置nil.
比如說, 異步發起一個網絡請求, 通常網絡返回有延時, 如果block中使用weakSelf, 那麼這個weakSelf有可能被置nil; 如果block中使用self, 那麼網絡返回時這個self不能置nil.
先來看下面的例子:
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.navigationController popViewControllerAnimated:NO];
});
// 模擬網絡請求
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0*NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
[self doSomething];
});
}
log:
-[ViewController2 doSomething]
-[ViewController2 dealloc]
我們看到, 雖然3秒後VC2界面退到VC, 但是VC2並沒有馬上被置nil, 而是等執行完block之後纔會置nil.
接着看第二個例子, 我們在block中使用weakSelf:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.navigationController popViewControllerAnimated:NO];
});
// 模擬網絡請求
__weak typeof(self) weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0*NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
[weakSelf doSomething];
sleep(2);
[weakSelf doAnotherThing];
});
log:
-[ViewController2 doSomething]
-[ViewController2 dealloc]
我們看到, 兩秒後打印了doSomething, 但是三秒後退出了界面, VC2被回收置nil, 導致doAnotherThing不執行 (此時weakSelf = nil).
爲了防止我們在block執行過程中, self被置nil, 我們需要使用__strong修飾符來強引用一下self (其實我們定義變量時系統默認就是強引用, 所以__strong修飾符可寫可不寫).
使用strong:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.navigationController popViewControllerAnimated:NO];
});
// 模擬網絡請求
__weak typeof(self) weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0*NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
[strongSelf doSomething];
sleep(2);
[strongSelf doAnotherThing];
});
log:
-[ViewController2 doSomething]
-[ViewController2 doAnotherThing]
-[ViewController2 dealloc]
我們看到, 2秒後調用了doSomething, 此時界面退出去, 但由於在block作用域中strongSelf一直存活, 所以VC2沒有馬上被置nil, 而是等到doAnotherThing調用後纔會被置nil.
如果在block回調之前, weakSelf被釋放了, 此時我們不想繼續執行代碼, 通常需要添加一個nil判斷:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.navigationController popViewControllerAnimated:NO];
});
// 模擬網絡請求
__weak typeof(self) weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0*NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (strongSelf) {
[strongSelf doSomething];
sleep(2);
[strongSelf doAnotherThing];
}
});
log:
-[ViewController2 dealloc]
綜上, weakSelf & strongSelf 使用法則是:
- 使用 weakSelf 來打破循環強引用.
- 使用 strongSelf 來使延長 weakSelf 的作用域 (保證在block內不爲nil).