我正在使用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
}
这是为什么?
答案 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
将是无效的引用。