在应用程序中,我想知道为什么在退出应用程序时没有调用类的 deinit
方法的实例。
例如,此处显示的 Test 类是在 AppDelegate 的 applicationDidFinishLaunching
中创建的。
import Cocoa
class Test {
let testVar = 1
init() {
print("Retain count \(CFGetRetainCount(self))")
NSApplication.shared().terminate(self)
}
deinit {
print("Calling deinit")
}
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
//@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
_ = Test()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
print("Terminating")
}
}
这样不仅调用Test的deinit
方法失败,而且Test的init
中的retain count为2;我原以为这是 1。
如果一个可选引用存储在 AppDelegate 类中并在创建 Test 实例时设置,则在调用 applicationWillTerminate
时它为 nil
有人可以解释为什么这里的保留计数是 2 以及如何确保在应用程序终止时调用 Test 的 deinit 吗?
最佳答案
我假设 Swift 的情况与此链接中记录的 Objective-C 情况相同: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH
“当应用程序终止时,可能不会向对象发送 dealloc 消息。因为进程的内存在退出时会自动清除,所以简单地让操作系统清理资源比调用所有内存管理方法更有效”
关于swift - 了解 AppDelegate 中的保留计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45105634/