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

Time:01-03

I'm trying to wrap my head around using ARC and the way it handles deallocation of memory. If I have some 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)
}

Do I need to worry about freeing up the space for the person or does ARC handle it? Do I need to declare a deinit in MyViewController?

CodePudding user response:

ARC handles deinitialization and deallocation for you once the referencing object is itself deallocated. Quoting from 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.

Your code demonstrates this as well: if I copy your code into a playground and add MyViewController() to create an instance of the class, I see Person Steve has been deallocated in the console output before the program exits.

  • Related