ios - 为什么会导致保留循环?
问题描述
我正在使用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
}
为什么是这样??
解决方案
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
将是无效的引用。
推荐阅读
- c# - 从使用派生类的泛型的类派生类
- java - Spring Batch 查找开始作业执行
- selenium-webdriver - 如何在 selenium-webdriver 的帮助下验证我的电子邮件字段
- vi - 如何使用 vi 对所有子目录中的文件进行搜索和替换?
- ios - 在 imageview 上自动布局 Imageview
- django - django1.11 无法与 oracle11g 连接
- c# - 如何将访问第三方服务的线程的返回数据动态传递给视图?
- erlang - 如何在 mod_muc_room.erl 中为 ejabberd 中的 opts 表字段 (muc_room) 添加自定义房间选项
- javascript - 无法使用 Parent 传递的值在子组件内设置状态
- python-3.x - 不可排序的类型:str() > int()