函数内部的函数保留周期



我想知道如何避免在以下情况下保留周期:

private func setupDismissCallbacks() {
// inner func     
func dismiss() {
self.videoExporter?.cancel()
self.rootViewController.dismiss(animated: true, completion: nil)
self.delegate?.childCoordinatorDidFinish(self)
}
// first clousre       
saveModalViewController.onButtonDismiss = {  [weak self] in
// not really using `self` here
guard let self = self else { return }
dismiss()
}
// second clousre  
saveModalViewController.onDimmedAreaDismiss = { [weak self] in
// not really using `self` here
guard let self = self else { return }
dismiss()
}
}

我有一个函数setupDismissCallbacks,它侦听来自saveModalViewControllerself 属性的两个回调。dismiss()setupDismissCallbacks内部的一个内部函数,我用它来访问self值。

但是在闭包onButtonDismissonDimmedAreaDismiss中,我无法访问self来调用dismiss,并且我无法将[weak self]添加到dismiss函数中,因为它是一个函数。

如何验证dismiss中的调用是否不会导致保留周期?

只需将闭包分配给局部变量即可。此时,提取dismiss是没有意义的,因此只需内联它:

private func setupDismissCallbacks() {     
let dismissCallback: () -> Void = {  [weak self] in
guard let self = self else { return }
self.videoExporter?.cancel()
self.rootViewController.dismiss(animated: true, completion: nil)
self.delegate?.childCoordinatorDidFinish(self)
}
saveModalViewController.onButtonDismiss = dismissCallback
saveModalViewController.onDimmedAreaDismiss = dismissCallback
}

>@Alexander评论中解释了这个问题:

您的内部函数捕获self。您的两个闭合捕捉到了这一点 内部函数(包括它所包含的上下文,其中包括self)。由于您的两个闭包被强烈引用saveModalViewController(我认为它被强烈引用self),您有一个保留周期。

您可以通过不dismiss捕获self来打破此循环。 将SaveCoordinator传递给dismiss

private func setupDismissCallbacks() {     
func dismiss(_ coordinator: SaveCoordinator) {
coordinator.videoExporter?.cancel()
coordinator(animated: true, completion: nil)
coordinator.delegate?.childCoordinatorDidFinish(coordinator)
}
// first clousre       
saveModalViewController.onButtonDismiss = {  [weak self] in
guard let self = self else { return }
dismiss(self)
}
// second clousre  
saveModalViewController.onDimmedAreaDismiss = { [weak self] in
guard let self = self else { return }
dismiss(self)
}
}

相关内容

  • 没有找到相关文章

最新更新