假設我們有一個給定的Swift類。在Swift Struct中刪除NotificationCenter Observer的最佳位置
class Test {
init() {
NotificationCenter.default.addObserver(...)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
在一個類中,你可以使用deinit
生命週期的方法來刪除NotificationCenter
觀察者。在一個結構中,沒有deinit
方法。因此我的問題是,有人會在結構中刪除NotificationCenter
觀察者?或者可能,我們不必刪除結構體中的觀察者嗎?
您可以讓結構保留對類的引用。當在類上調用'dealloc'時,您知道結構已被釋放。 – JAL