Swift基础之09循环引用解决

1,普通循环引用解决: 在定义的时候加上weak修饰即可
  • unowned修饰也可以解决部分循环引用,但是注意:unowned是不能修饰可选类型的
class Person{
    var name: String = ""
    var age: Int = 0
    var book: Book?
    deinit {
        print("person---deinit")
    }
}

class Book{
    var bookName: String = ""
    var price: Float = 0
    //在下面这个位置进行弱引用即可
    weak var owner: Person?
    deinit {
        print("book----deinit")
    }
}

var person: Person? = Person.init()
var book: Book? = Book.init()

//为什么具体类型可以赋值给可选类型???
book?.owner = person
person?.book = book

book = nil
person = nil
2,闭包循环引用解决:
  • 解决循环引用方法01:weak var weakself = self
weak var weakself = self
httptool.loadData { (jsondata) in
    print(jsondata)
    weakself?.view.backgroundColor = UIColor.red
}
  • 解决循环引用方法02:(相当于第一种方法的简便写法)
httptool.loadData { [weak self] (jsondata) in
    print(jsondata)
    self?.view.backgroundColor = UIColor.red
}

  • 解决循环引用方法03:(相当于unratain unsafe,可能会有僵尸对象的问题),一般不用这

unowned是不能修饰可选类型的,这一点需要注意

httptool.loadData { [unowned self] (jsondata) in
    print(jsondata)
    self.view.backgroundColor = UIColor.red
}

你可能感兴趣的:(Swift基础之09循环引用解决)