weak var person: Person? unowned let person: Person
unowned var person: Person
weak: 必须为var,必须为可选性(一定得有'?')。对象释放后,weak指针会自动置为nil。
unowned:不可以是可选性(一定不可以有'?')。对象释放后,unowned指针不会自动置为nil。
class Person { var name: String var dog: Dog? init(name: String) { self.name = name print("person initializa") } deinit{ print("person deinitialize") } } class Dog { var name: String weak var person: Person? init(name: String) { self.name = name print("dog initializa") } deinit{ print("dog deinitialize") } } var person: Person? = Person(name: "Tom") var dog: Dog? = Dog(name: "Taidi")
dog.person = person person = nil dog?.person // nil dog = nil
class Person { var name: String var dog: Dog? init(name: String) { self.name = name print("person initializa") } deinit{ print("person deinitialize") } } class Dog { var name: String unowned var person: Person init(name: String, person: Person) { self.name = name self.person = person print("dog initializa") } deinit{ print("dog deinitialize") } } var person: Person? = Person(name: "Tom") var dog: Dog? = Dog(name: "Taidi", person: person!) person = nil dog?.person // 会崩溃 dog = nil