如果声明了 deinit,ARC 是否会释放 class 或它是否保留引用?

Does ARC deallocate a class if deinit has been declared or does it maintain the reference?

我正在尝试使用 ARC 及其处理内存释放的方式。如果我有一些 class:

class Person {
      var name: String = ""
      var age: Int = 0

      init(name: String, age: Int) {
         self.name = name
         self.age = age
     }

     deinit {
         print("Person \(name) has been deallocated")
     }
}



class MyViewController: UIViewController {
    var person = Person(name: "Steve", age: 85)
}

我需要担心为这个人释放 space 还是 ARC 会处理它?我需要在 MyViewController 中声明一个 deinit 吗?

一旦引用对象本身被解除分配,ARC 就会为您处理解除初始化和解除分配。引用自 https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html:

…ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.

…whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes a strong reference to the instance. The reference is called a “strong” reference because it keeps a firm hold on that instance, and doesn’t allow it to be deallocated for as long as that strong reference remains.

您的代码也证明了这一点:如果我将您的代码复制到操场并添加 MyViewController() 以创建 class 的实例,我会在控制台输出中看到 Person Steve has been deallocated在程序退出之前。