目录
- 概述
- 自定义block
- 系统block
- 何时使用 weakSelf & strongSelf ?
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]
且系统抛出警告:
情况四.png
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).
网友评论