swift中解決閉包迴圈引用的幾種方式
import UIKit
class ViewController: UIViewController {
// VC --strong -- 閉包
// 閉包- strong -- VC
//定義屬性閉包
//swift 屬性的預設就是強引用
var finishedCallback: ((res: String) -> ())?
overridefunc viewDidLoad() {
super.viewDidLoad()
loadData { [unowned self] (result) in
print(result,self)
}
}
// [unowned self]
func methodInSwift2() {
loadData { [unowned self] (result) in
print(result,self)
}
}
//[weak self] 和 __weak typeof(self) 作用類似 -> 物件被回收是記憶體地址會自動指向nil 更加安全推薦使用這種方式
func methodInSwift1() {
loadData { [weak self] (result) in
print(result,self)
}
}
func methodInOC() {
//1. 仿照OC 解決
//弱引用的物件又一次執行 nil的機會
weakvar weakSelf = self
loadData { (result) in
print(result,weakSelf)
}
}
func loadData(finished: (result: String) -> () ) {
finishedCallback = finished
dispatch_async(dispatch_get_global_queue(0,
NSThread.sleepForTimeInterval(3)
//在主佇列回撥
dispatch_async(dispatch_get_main_queue(), {
//執行閉包
finished(result: "辦證: 13581850000")
})
}
}
//dealloc OC
//解構函式
deinit {
print("886")
}
}