2

I've got the following code:

class Company {
    let name: String
    var founder: Person?

    init(name: String) {
        self.name = name
        print("\(self.name) was initialized")
    }

    deinit {
        print("\(self.name) was deinitialized")
    }
}

class Person {
    let name: String
    weak var company: Company?

    init(name: String) {
        self.name = name
        print("\(self.name) was initialized")
    }

    deinit {
        print("\(self.name) was deinitialized")
    }
}

var mark: Person?
var facebook: Company?

mark = Person(name: "Mark Zuckerberg")
facebook = Company(name: "Facebook")
mark!.company = facebook
facebook!.founder = mark

facebook = nil
mark = nil

I've got a weak reference to person, but it still seems like there's a retain cycle because neither one of those instances is being deinitialized. It prints out the initialization statement but not the deinitializing ones.

Output:

Mark Zuckerberg was initialized
Facebook was initialized
MickeyTheMouse
  • 419
  • 3
  • 5
  • 13
  • 2
    What is your running environment? I tested with a macOS CLI app and the `deinit` does run and print the text. – Ricky Mo Nov 07 '18 at 07:42
  • I can reproduce this behaviour in the playground. – Sweeper Nov 07 '18 at 07:47
  • 1
    This post has answer to your question [https://stackoverflow.com/a/24363716/10317684](https://stackoverflow.com/a/24363716/10317684) – Ricky Mo Nov 07 '18 at 07:48
  • 2
    Possible duplicate of [Deinit method is never called - Swift playground](https://stackoverflow.com/questions/24363384/deinit-method-is-never-called-swift-playground) – Kamran Nov 07 '18 at 07:57

1 Answers1

0

For this example, if you assign object variables with optional chaining and instantiate them inside a code block, they will be deinitialized when there is no strong reference to that object. ARC Documentation

class Company {
    let name: String
    var founder: Person?

    init(name: String) {
        self.name = name
        print("\(self.name) was initialized")
   }

    deinit {
        print("\(self.name) was deinitialized")
    }
}

class Person {
    let name: String
    weak var company: Company?

    init(name: String) {
        self.name = name
        print("\(self.name) was initialized")
    }

    deinit {
        print("\(self.name) was deinitialized")
    }
}

do{
    var mark: Person?
    var facebook: Company?

    mark = Person(name: "Mark Zuckerberg")
    facebook = Company(name: "Facebook")
    mark?.company = facebook
    facebook?.founder = mark
}
Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37