class Person {
var name:String
init(name:String) {
self.name = name
}
//析构函数
deinit{
print("内存已经释放")
}
}
引用计数为0的时候系统会自动内存释放,
自动释放内存在遇到强引用循环的时候不会起作用。
用
week
或者unowned
可破
class Person {
var name: String
var apartement: Apartment?
init(name: String) {
self.name = name
print("person has been initialized")
}
deinit{
print("person has been deIInitalized")
}
}
class Apartment {
let name: String
//week 需要 var与可选型
week var tenant: Person?
//unowned 不需要 不能为空!
unowned let place: String
init(name: String) {
self.name = name
print("apartment has been initialized")
}
deinit {
print("apartment has been deinitialized")
}
}
week
在闭包中使用self
可能会产生强引用循环,造成内存泄漏
class SmartAirConditioner {
var temperature: Int = 26
var temperatureChange: ((Int) -> () )!
init() {
//捕获列表
temperatureChange = { [unowned self ] newTemperature in
if abs(newTemperature - self.temperature) >= 10 {
print("abc")
}else {
self.temperature = newTemperature
}
}
}
}
网友评论