晚上好。
我对在 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)
如果 self
为 nil
,则根本不会调用该函数。
关于ios - 当 self 在转义闭包中很弱时,在 self 函数中调用 self 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57972211/