swift - 了解 AppDelegate 中的保留计数

标签 swift macos memory-leaks retain

在应用程序中,我想知道为什么在退出应用程序时没有调用类的 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/

相关文章:

macos - 将导航按钮添加到统一标题栏/工具栏

html - 让 OSX Safari 支持 css "white-space: pre"

java - 在循环中创建位图时发生内存泄漏

ios - 在 Swift 中将 [NSDate date] 分配给 NSString

ios - iOS 中的 UITextField 允许单个数字

ios - 什么是 iOS 版本的 firebase 列表适配器?

ios - 在 Swift 中初始化一个具有多种值类型的数组

iphone - TFS 与 Mac 操作系统

memory-leaks - WP8 LongListSelector内存泄漏

c++ - 用宏替换 new 与放置 new 冲突