一个难题:弱引用在Swift 4中不起作用?

时间:2018-10-05 21:01:59

标签: swift swift-playground

我已经在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

那是为什么?

1 个答案:

答案 0 :(得分:2)

我认为这与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