为什么会导致保留循环?
Why is a retain cycle being caused?
我正在使用 Eureka 设置我的 table 视图。我有一个带有 header:
的部分
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:)
[=10=].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
}
这是为什么?
header.onSetupView = strongSelf.setUpHeader(view:section:)
这一行创建了对 strongSelf
的强引用,这是对 self
的强引用,因此在 onSetupView
中创建了对 self
的强引用关闭。
换句话说,你在这里写的是一样的:
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
将是无效引用。
我正在使用 Eureka 设置我的 table 视图。我有一个带有 header:
的部分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:)
[=10=].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
}
这是为什么?
header.onSetupView = strongSelf.setUpHeader(view:section:)
这一行创建了对 strongSelf
的强引用,这是对 self
的强引用,因此在 onSetupView
中创建了对 self
的强引用关闭。
换句话说,你在这里写的是一样的:
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
将是无效引用。