2018年2月26日更新
最近在項(xiàng)目用到了 weak | unowned 又有些思考.
大部分情況推薦使用weak
舉個(gè)栗子
var bossView: BossView?
// 比較好的處理方式
bossView = BossView()
bossView.tmpView.selectBlock = { [weak bossView] _ in
bossView?.tmpView.name = "Tony"
}
// 或者
bossView = BossView()
bossView.tmpView.selectBlock = { [weak bossView] _ in
guard let weakView = bossView else { return }
weakView.tmpView.name = "Tony"
}
// 有一定的崩潰可能
// bossView = BossView()
tmpView.selectBlock = { [unowned bossView] _ in
bossView.tmpView.name = "Tony"
// bossView為屬性等情況, 如果bossView為nil 則崩潰.
}
歷史紀(jì)錄:
1. Objective-C中的block避免循環(huán)引用的方法
__weak typeof(self) weakSelf = self;
self.block = ^{
__strong typeof(self) strongSelf = weakSelf;
[strongSelf doSomething];
};
2. Swift使用weak避免循環(huán)引用
一般使用weak的處理不是很優(yōu)雅可能如下:
self.closure = { [weak self] in
self?.doSomeThing()
}
使用 self?. 如果閉包中判斷比較多,數(shù)據(jù)處理復(fù)雜難免會(huì)有使用 ! 強(qiáng)解包的情況, 所以很不優(yōu)雅也有一定風(fēng)險(xiǎn).
故而可以用 guard 處理一下
self.closure = { [weak self] in
guard let weakSelf = self { return }
// 之后正常使用weakSelf代替self
weakSelf.doSomeThing()
}
不過按照官方文檔的推薦使用unowned應(yīng)該更為合理.
3. Swift中使用unowned避免循環(huán)引用
// 請(qǐng)拼了老命保證self不是nil.
// 換句話說自己引用自己可以用unowned,自己引用其他人, 都不值得信任. 請(qǐng)weak
self.closure = { [unowned self] in
self.doSomething()
}
2017.7.18. by xiaozao