首页 > 解决方案 > 为什么会导致保留循环?

问题描述

我正在使用Eureka来设置我的表格视图。我有一个带有标题的部分:

Section() { [weak self] in
    guard let strongSelf = self else { return }
    var header = HeaderFooterView<MyView>(.nibFile(name: "MView", bundle: nil))
    header.onSetupView = strongSelf.setUpHeader(view:section:)
    $0.header = header
    ...
}

private func setUpHeader(view: MyView, section: Section) {
    // content here doesn't seem to make a difference.
}

出于某种原因,它总是在线上设置一个保留周期header.onSetupView = strongSelf.setUpHeader(view:section:)。如果我将代码从setUpHeader(view: MyView, section: Section)函数移动到这样的块中,则没有保留周期:

header.onSetupView = { [weak self] view, section in

}

为什么是这样??

标签: iosswifteureka-forms

解决方案


header.onSetupView = strongSelf.setUpHeader(view:section:)

此行创建了对 的强引用strongSelf,这是对 的强引用,因此可传递地在闭包self中创建强引用。selfonSetupView

换一种说法,你在这里写的和下面的一样:

header.onSetupView = { view, section in
    strongSelf.setupHeader(view: view, section: section)
}

由于strongSelf是对 的强引用self,因此与对 的强引用是一回事self

header.onSetupView = { view, section in
    self.setupHeader(view: view, section: section)
}

还有另一种说法:self不能在之前释放strongSelf,因为那时strongSelf将是无效的引用。


推荐阅读