unowned
unowned要求被捕获的变量不能为nil,所以在closure中使用[unowned self] 必须保证self不能为空,所以当self被释放后再执行closure会导致程序崩溃。
let tapBackground = UITapGestureRecognizer()
tapBackground.rx.event.subscribe(onNext: {[unowned self] _ in
self.view.endEditing(true)
}).disposed(by: disposeBag)
view.addGestureRecognizer(tapBackground)
weak
weak允许被捕获的值为可选型,即可以被捕获的值为nil,当使用[weak self]时需要进行对self进行解包。或者使用
guard let strongSelf = self else { return }
let tapBackground = UITapGestureRecognizer()
tapBackground.rx.event.subscribe(onNext: {[weak self] _ in
self?.view.endEditing(true)
}).disposed(by: disposeBag)
view.addGestureRecognizer(tapBackground)
网友评论