这个闭包会导致内存泄漏吗? [英] Will this closure cause a memory leak?
本文介绍了这个闭包会导致内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道以下会导致内存泄漏,因为 MyClass
和 myClosure
相互引用.
I know that the following causes a memory leak because MyClass
and myClosure
references each other.
var MyClass {
var myVar = 0
let myClosure: (Int) -> Void
init() {
self.myClosure = { x in
self.myVar = x
}
}
}
以下是否也会导致内存泄漏?为什么或为什么不?
Does the following cause a memory leak as well? Why or why not?
var MyClass {
var myVar = 0
function myFunc() {
let myClosure = { x in
self.myVar = x
}
myClosure(0)
}
}
推荐答案
声明weak self以避免内存泄漏并保护self以避免调用deallocated self
Declare weak self to avoid memory leak and guard self in order to avoid calling deallocated self
func myFunc() {
let myClosure = { [weak self] x in
guard let strongSelf = self else {
return
}
strongSelf.myVar = x
}
myClosure(0)
}
这篇关于这个闭包会导致内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文