swift中闭包引起的循环引用

unowned

[unowned self] 和 __unsafe__retained作用类似 -> 对象被回收是 内存地址不会自动指向nil 会造成野指针访问

func methodInSwift2() {
        loadData { [unowned self] (result) in
            print(result,self)
        }
    }

weak

[weak self] 和 __weak typeof(self) 作用类似 -> 对象被回收是 内存地址会自动指向nil 更加安全 推荐使用这种方式

    func methodInSwift1() {
        loadData { [weak self] (result) in
            let strongSelf = self {
                print(result,self)
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/houboye/article/details/86488167
今日推荐