示例代码:
import UIKit
class ViewController: UIViewController {
// 定义闭包
var callback:(()->())?
override func viewDidLoad() {
super.viewDidLoad()
// 闭包实现
callback = {
print(weakSelf?.view)
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// 执行闭包
callback?()
}
deinit{
print("ViewController再见")
}
}
分析:
当前控制器 强引用了闭包
闭包强引用self
A -> B B -> A
解决循环引用:
- 方法01(仿照OC的写法) (等同于OC中 __weak)
weak var weakSelf = self
callback = {
print(weakSelf?.view)
}
- 方法02 (等同于OC中 __weak) (iOS时间- 5.0) 推荐方式
callback = {[weak self] in
print(self?.view)
}
- 方法03 (等同于OC中 __unsafe_unretained)(iOS时间- 4.0)
缺点:self不是可选项,如果self已经被释放,则出现野指针访问
callback = {[unowned self] in
print(self.view)
}