iOS開(kāi)發(fā)中block直接強(qiáng)引用和先弱引用再?gòu)?qiáng)引用的區(qū)別
__weak是為了解決循環(huán)引用
如果一個(gè)對(duì)象A持有了一個(gè)block,同時(shí)block內(nèi)又持有了對(duì)象A,為了解決循環(huán)引用我們要在用__weak修飾完對(duì)象A后再去持有它,這樣就解決了循環(huán)引用。
__strong是為了防止block持有的對(duì)象提前釋放
看代碼:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self dismissViewControllerAnimated:YES completion:nil];
__weak typeof(self) weakSelf = self;
self.block = ^{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"%@", weakSelf);
});
};
self.block();
}
點(diǎn)擊屏幕,當(dāng)前控制器消失,同時(shí)被銷毀掉,5秒后打印的weakSelf就是一個(gè)(null)。
而我們?nèi)绻赽lock內(nèi)使用__strong后就能保證再打印完strongSelf之后再釋放當(dāng)前控制器。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self dismissViewControllerAnimated:YES completion:nil];
__weak typeof(self) weakSelf = self;
self.block = ^{
__strong typeof(self) strongSelf = weakSelf;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"%@", strongSelf);
});
};
self.block();
}
目前也就找到個(gè)block內(nèi)部使用GCD,GCD中使用weakSelf再現(xiàn)了self提前釋放的例子。