1、两个属性都允许为nil
生命周期中会变为nil,使用弱引用,一定是可选类型的,设置为nil时,不会调用属性观察者
class Person{
let name:String
var apartment:Apartment?
init(name:String) {
self.name = name
}
deinit {
NSLog("Customer deinit")
}
}
class Apartment{
let unit:String
weak var person:Person?
init(unit:String) {
self.unit = unit
}
deinit {
NSLog("CreditCard deinit")
}
}
2、一个属性允许为nil,另一个属性不允许为nil
初始化赋值后再也不会被赋值为nil的实例,使用无主引用,非可选类型,不允许设置为nil.
试图在实例被释放后访问无主引用,将触发运行时错误。试图访问引用的实例已经被释放了的无主引用,会crash.
class Customer{
let name:String
var card:CreditCard?
init(name:String) {
self.name = name
}
deinit {
NSLog("Customer deinit")
}
}
class CreditCard{
let number:UInt64
unowned let customer:Customer
init(number:UInt64,customer:Customer) {
self.number = number
self.customer = customer
}
deinit {
NSLog("CreditCard deinit")
}
}
3、两个属性都不能为nil,需要一个类使用无主属性,另一个类使用隐式展开的可选属性(属性后有!)
class Country{
let name:String
var capCity:City!//隐式展开的可选属性
init(name:String,capCityName:String) {
self.name = name
self.capCity = City.init(name: capCityName, country: self)
}
deinit {
NSLog("Country deinit")
}
}
class City{
let name:String
unowned let country:Country
init(name:String,country:Country) {
self.name = name
self.country = country
}
deinit {
NSLog("City deinit")
}
}
网友评论