3

I'mm trying to learn how ARC works exactly, so I read Swift ARC documentation and I followed the example that they provide in the document using playground:

class Person {
    let name: String
    weak var apartment: Apartment?

    init(name: String) { self.name = name }
    deinit { print("\(name) is being deinitialized") }
}

class Apartment {
    let unit: String
    weak var tenant: Person?

    init(unit: String) { self.unit = unit }
    deinit { print("Apartment \(unit) is being deinitialized") }
}

var john: Person?
var unit4A: Apartment?
john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")
john?.apartment = unit4A
unit4A?.tenant = john

john = nil
unit4A = nil

My question is why when I call Person instance john optional:

john?.apartment = unit4A

the object become deallocated, but when I call it force unwrapped:

john!.apartment = unit4A

it will not become deallocated.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
A.Munzer
  • 1,890
  • 1
  • 16
  • 27
  • 3
    Probably related to how Playgrounds handles object references (e.g., incremental compilation, object inspection, etc). Try running this on a regular Xcode project instead (for instance, a simple command line app). – Paulo Mattos Feb 17 '19 at 10:50

1 Answers1

2

Testing your code in a simple Xcode project worked just fine, this is a problem related to playgrounds handling objects.

However a when a deinit is not called its probably a retain cycle problem, because the ARC is not able to deallocate strong references, therefore wont be deallocated.

Check out this answer .
Also read more about retain cycles here

Mohmmad S
  • 5,001
  • 4
  • 18
  • 50