Closures
Closures 导致循环引用的原因是:Closures对使用它们的对象有一个强引用。
比如:
class Example {
private var counter = 0
private var closure : (() -> ()) = { }
init() {
closure = {
self.counter += 1
print(self.counter)
}
}
func foo() {
closure()
}
}
此时,对象对closure有一个强引用,同时在closure的代码块中又对该对象本身有一个强引用。这样就引起了循环引用的发生。
这种情况,可以有两种方法来解决这个问题。
1.使用[unowned self]:
class Example {
private var counter = 1
private var closure : (() -> ()) = { }
init() {
closure = { [unowned self] in
self.counter += 1
print(self.counter)
}
}
func foo() {
closure()
}
}
使用[unowned self] 的时候需要注意的一点是:调用closure的时候如果对象已经被释放的话,会出现crash。
2.使用[weak self]:
class Example {
private var counter = 1
private var closure : (() -> ()) = { }
init() {
closure = { [weak self] in
self?.counter += 1
print(self?.counter ?? "")
}
}
func foo() {
closure()
}
}
[weak self] 和[unowned self] 的区别是 [weak self]处理的时候是一个可选类型。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。
注:相关教程知识阅读请移步到swift教程频道。








