14.7 Swift中unowned解决循环强引用

前端之家收集整理的这篇文章主要介绍了14.7 Swift中unowned解决循环强引用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

/**

7unowned 解决循环强引用

仍然使用官方的例子来给大家讲解

*/

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

猜你在找的Swift相关文章