一个难题:弱引用在 Swift 4 中不起作用?
A puzzle: weak reference not working in Swift 4?
我在 Playground 中创建了以下两个 类,并希望它们在超出范围后都可以解除分配(因为引用很弱)。但令我惊讶的是他们没有!有人可以阐明这个难题吗?提前谢谢你。
代码如下:
class User {
var name: String
weak var phone: Phone?
init(name: String) {
self.name = name
print("User \(name) is initialized")
}
deinit {
print("User \(name) is deallocated")
}
}
class Phone {
let model: String
weak var user: User?
init(model: String) {
self.model = model
print("Phone \(model) is initialized")
}
deinit {
print("Phone \(model) is deallocated")
}
}
do {
let user1 = User(name: "John")
let phone1 = Phone(model: "iPhone7")
user1.phone = phone1
phone1.user = user1
}
print("Done")
这是显示未调用 deinit() 的输出,尽管 类 超出范围:
User John is initialized
Phone iPhone7 is initialized
Done
这是为什么?
我认为这与 Playgrounds 处理代码的方式有关。它没有完全相同的生命周期,您不能期望在代码完成后释放变量 运行。
如果您使对象成为可选对象,一切都会按预期解除分配:
do {
let user1: User? = User(name: "John")
let phone1: Phone? = Phone(model: "iPhone7")
user1?.phone = phone1
phone1?.user = user1
}
User John is initialized
Phone iPhone7 is initialized
Phone iPhone7 is deallocated
User John is deallocated
Done
我在 Playground 中创建了以下两个 类,并希望它们在超出范围后都可以解除分配(因为引用很弱)。但令我惊讶的是他们没有!有人可以阐明这个难题吗?提前谢谢你。
代码如下:
class User {
var name: String
weak var phone: Phone?
init(name: String) {
self.name = name
print("User \(name) is initialized")
}
deinit {
print("User \(name) is deallocated")
}
}
class Phone {
let model: String
weak var user: User?
init(model: String) {
self.model = model
print("Phone \(model) is initialized")
}
deinit {
print("Phone \(model) is deallocated")
}
}
do {
let user1 = User(name: "John")
let phone1 = Phone(model: "iPhone7")
user1.phone = phone1
phone1.user = user1
}
print("Done")
这是显示未调用 deinit() 的输出,尽管 类 超出范围:
User John is initialized
Phone iPhone7 is initialized
Done
这是为什么?
我认为这与 Playgrounds 处理代码的方式有关。它没有完全相同的生命周期,您不能期望在代码完成后释放变量 运行。
如果您使对象成为可选对象,一切都会按预期解除分配:
do {
let user1: User? = User(name: "John")
let phone1: Phone? = Phone(model: "iPhone7")
user1?.phone = phone1
phone1?.user = user1
}
User John is initialized
Phone iPhone7 is initialized
Phone iPhone7 is deallocated
User John is deallocated
Done