gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:26:15 27 4
gpt4 key购买 nike

晚上好。

我对在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com