Search code examples
swiftautomatic-ref-countingoption-typedeinit

How ARC act with force unwrapped instance


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.


Solution

  • 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