swift 闭包循环引用

时间:2022-10-30 16:55:38

  当使用闭包时,类本身持有self,然后又在闭包中访问了self或者self的属性,就会导致恶心额循环引用。swift提供的解决方法是在闭包中定义捕获列表,捕获列表是闭包想怎么引用捕获来的变量。例如下面定义了一个捕获列表,引用self为unowned引用,这样在宾傲中用self就不会导致循环引用

    let name = "cyy"
lazy var someClosure: (Int, String) -> String = {
[unowned self](index: Int, stringToProcess: String) -> String in
print(stringToProcess + self.name)
return self.name
}
//打印的值为:
//lllcyy
//deinit >>><kuaixiaoyigou.LoginViewController: 0x7fde8a40acb0>

去掉捕获列表

let name = "cyy"
lazy var someClosure: (Int, String) -> String = {
(index: Int, stringToProcess: String) -> String in
print(stringToProcess + self.name)
return self.name
}
//打印值:
//lllcyy 没有调用deinit