/**
(7)unowned 解决循环强引用
仍然使用官方的例子来给大家讲解
*/
class Customer {
let name: String
// 可选值,对于人来说信用卡可有可无
var card: CreditCard?
init(name: String) {
self.name = name
}
deinit {
print("\(name) is being deinitialized")
}
}
class CreditCard {
let number: UInt64
// 对于信用卡来说,一定要有主人,而且是唯一的 unowned(非可选类型),根据题意不要用weak修饰了。
unowned let customer: Customer
init(number: UInt64,customer: Customer) {
self.number = number
self.customer = customer
}
deinit {
print("Card #\(number) is being deinitialized")
}
}
/**
把 unowned 去掉后就是变成了循环强引用了。
不会被销毁,没有出现打印
加上 unowned 打印出现
John Appleseed is being deinitialized
Card #12344556233 is being deinitialized
*/
var john: Customer?
john = Customer.init(name: "John Appleseed")
john!.card = CreditCard.init(number: 1234_4556_233,customer: john!)
john = nil
原文链接:https://www.f2er.com/swift/322362.html