[英]Retain Cycle in closure
I try to implement some variant of Coordinator pattern, but I face problem with retain cycle in closure.我尝试实现 Coordinator 模式的一些变体,但我在关闭时遇到了保留循环的问题。 It looks like that:它看起来像这样:
func goTo() {
let coord = SecondViewCoordinator(nav: navigationController)
add(coord)
coord.start()
coord.deinitIfNeeded = { [weak self] in
guard let self = self else { return }
self.free(coord)
}
}
As you can see I set deinitIfNeeded
and then, if in SecondViewCoordinator
call deinitIfNeeded?()
controller pops correctly, but reference to SecondViewCoordinator
is still exist even though childCoordinators
array is empty.如您所见,我设置了deinitIfNeeded
,然后,如果在SecondViewCoordinator
调用deinitIfNeeded?()
控制器正确弹出,但即使childCoordinators
数组为空,对SecondViewCoordinator
引用仍然存在。
My Coordinator class looks like that:我的 Coordinator 类看起来像这样:
class Coordinator {
weak var navigationController: UINavigationController?
var childCoordinators: [Coordinator] = []
var deinitIfNeeded: (() -> ())?
init(nav: UINavigationController?) {
self.navigationController = nav
}
func add(_ coordinator: Coordinator) {
childCoordinators.append(coordinator)
}
func free(_ coordinator: Coordinator) {
childCoordinators = childCoordinators.filter({ $0 !== coordinator })
}
}
memory graph presents this:内存图显示了这个:
any ideas?有任何想法吗?
In在
coord.deinitIfNeeded = { [weak self] in
guard let self = self else { return }
self.free(coord)
}
You are holding a strong reference to coord
inside the closure.您在闭包内持有对coord
的强引用。 Try something like this;尝试这样的事情;
coord.deinitIfNeeded = { [weak self, weak coord] in
guard let self = self, let coord = coord else { return }
self.free(coord)
}
The memory graph is giving a hint that this is the case (the right side says the strong reference is in a closure).内存图暗示了这种情况(右侧表示强引用在闭包中)。
You could also set coord.deinitIfNeeded
to nil
inside the closure.您还可以在闭包内将coord.deinitIfNeeded
设置为nil
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.