[英]Invoking a self parameter in a self function when self is weak inside a escaping closure
Good evening. 晚上好。
I come bearing a doubt about escaping (asynchronous) closures in Swift, and I'd want to know which would be the best way to solve it. 我开始对在Swift中转义(异步)闭包感到怀疑,我想知道哪种是解决它的最佳方法。
There's an example function. 有一个示例函数。
func exampleFunction() {
functionWithEscapingClosure(onSuccess: { result in
self.anotherFunction(parameter: self.parameter, result: result)
}
}
As you've probably noticed, this will cause a memory leak, since onSuccess is an escaping closure and it's retaining self. 您可能已经注意到,这将导致内存泄漏,因为onSuccess是一个转义的闭包,并且保留了self。
Now, the way to solve it is adding [weak self] in the closure. 现在,解决问题的方法是在闭包中添加[弱自我]。 And I want anotherFunction to be invoked only if self isn't nil, so it would be like that:
而且我希望只有在self不为nil时才调用anotherFunction,所以就像这样:
func exampleFunction() {
functionWithEscapingClosure(onSuccess: { [weak self] result in
self?.anotherFunction(parameter: self.parameter, result: result)
}
}
But the parameter is an issue, since I can't pass on a nil parameter, I have to unwrap self to use the parameter. 但是参数是一个问题,因为我不能传递nil参数,所以我必须解开自身才能使用该参数。
Would it be safe to use a force unwrap ( self!.parameter
), since the function only gets called if self is not nil? 使用强制解包(
self!.parameter
)是否安全,因为该函数仅在self不为nil时才被调用? Should I perform a variable binding for self?.parameter
before calling self?.anotherFunction
? 我应该在调用
self?.parameter
之前为self?.parameter
执行变量绑定self?.anotherFunction
?
Thanks in advance! 提前致谢!
Yes, you can write 是的,你可以写
self?.anotherFunction(parameter: self!.parameter, result: result)
If self
is nil
the function isn't called at all. 如果
self
为nil
,则根本不调用该函数。
Let's use this after your capture list 让我们在捕获列表之后使用它
guard let `self` = self else { return }
Your function should be like this: 您的功能应如下所示:
func exampleFunction() {
functionWithEscapingClosure(onSuccess: { [weak self] result in
guard let `self` = self else { return }
self.anotherFunction(parameter: self.parameter, result: result)
}
}
So, dont worry about the optional (?) anymore. 因此,不再担心可选(?)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.