我正在探索内存管理概念并发现
deinit
方法未在 Xcode 10 beta 6游乐场中调用。最初,我认为可能是代码中的一些问题。然后,我在Xcode 9.4.1 Playground和Xcode 10 beta 6示例应用程序中测试了相同的代码,一切都按预期工作(调用了deinit方法)。是 Xcode 10 beta 6游乐场中的错误还是其他错误?我正在使用Apple开发人员的代码-
class Person {
let name: String
weak var apartment: Apartment?
init(name: String) {
self.name = name
print("\(name) is being initialized")
}
deinit { print("\(name) is being deinitialized") }
}
class Apartment {
let unit: String
weak var tenant: Person?
init(unit: String) { self.unit = unit
print("Apartment \(unit) is being initialized")
}
deinit { print("Apartment \(unit) is being deinitialized") }
}
do {
var john: Person?
var unit4A: Apartment?
john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john
john = nil
unit4A = nil
}
答案 0 :(得分:2)
This issue seems to still be present in Xcode 10.0 (10A255). I have playground with the following code:
class Person {
var name: String
func buy(car: Car) {
car.owner = self
}
init(name: String) {
self.name = name
print("Person \(name) is initalized")
}
deinit {
print("Person \(name) is being deinitialized")
}
}
class Car {
let model: String
weak var owner: Person?
init(model: String) {
self.model = model
print("Car \(model) is initialized")
}
deinit {
print("Car \(model) is being deinitialized")
}
}
print("===== before do =====")
do {
print(" ---- do begin -----")
let johnny = Person(name: "John")
let porsche = Car(model: "Carrera4")
johnny.buy(car: porsche)
print(" ---- do end -----")
}
print("===== after do =====")
In Xcode 9.4.1 both Car's and Person's deinit are executed, but in Xcode 10.0 (10A255) the Person's deinit method is not executed.
The same code inside a test macOS project works as expected (both deinit executed) in Xcode 9.4.1 as well as Xcode 10.0 (10A255)