ios - 当 self 在转义闭包中很弱时,在 self 函数中调用 self 参数

标签 ios swift closures

晚上好。

我对在 Swift 中转义(异步)闭包有疑问,我想知道哪种方法是解决它的最佳方法。

有一个示例函数。

func exampleFunction() {
   functionWithEscapingClosure(onSuccess: { result in
      self.anotherFunction(parameter: self.parameter, result: result)
   }
}

您可能已经注意到,这会导致内存泄漏,因为 onSuccess 是一个转义闭包并且它会保留自己。

现在,解决它的方法是在闭包中添加[weak self]。我希望仅当 self 不为 nil 时才调用 anotherFunction,所以它会像这样:

func exampleFunction() {
   functionWithEscapingClosure(onSuccess: { [weak self] result in
      self?.anotherFunction(parameter: self.parameter, result: result)
   }
}

但是参数是个问题,因为我不能传递 nil 参数,所以我必须解包 self 才能使用参数。

使用强制展开 (self!.parameter) 是否安全,因为只有当 self 不为 nil 时才会调用该函数? 我是否应该在调用 self?.anotherFunction 之前为 self?.parameter 执行变量绑定(bind)?

提前致谢!

最佳答案

是的,你可以写

self?.anotherFunction(parameter: self!.parameter, result: result)

如果 selfnil,则根本不会调用该函数。

关于ios - 当 self 在转义闭包中很弱时,在 self 函数中调用 self 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57972211/

相关文章:

javascript - 如何为 JavaScript 函数提供特定上下文而不立即调用它

ios - 如何在 Sprite Kit 中创建边界

iOS - 防止对象重新分配

ios - NSURL 请求不起作用

iOS:跨viewControllers在导航栏下方添加 View

ios - 如何删除内容和弹出箭头之间的白色区域ios

ios - 警告 : could not load any Objective-C class information in Swift realm

使用闭包时 Swift 惰性存储属性与常规存储属性

Javascript - 命名空间与闭包之间的区别?

ios - 如何遍历字典,通过快速按下按钮加载下一个项目