为什么会引起保留周期?

时间:2018-11-19 15:46:46

标签: ios swift eureka-forms

我正在使用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

}

这是为什么?

1 个答案:

答案 0 :(得分:1)

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

此行创建对strongSelf的强引用,而对self的强引用,因此可传递性地在self闭包中创建对onSetupView的强引用。

换一种说法,您在此处编写的内容与以下内容相同:

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将是无效的引用。