美文网首页
Swift 循环引用

Swift 循环引用

作者: EASXAI | 来源:发表于2021-12-30 13:30 被阅读0次

    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)

    更多理解可查阅
    https://blog.csdn.net/weixin_34191734/article/details/89050930?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ELandingCtr%7Edefault-1.queryctr&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ELandingCtr%7Edefault-1.queryctr&utm_relevant_index=1

    相关文章

      网友评论

          本文标题:Swift 循环引用

          本文链接:https://www.haomeiwen.com/subject/gqpiqrtx.html