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
  • 389
  • 2
  • 4
  • 12

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,032
  • 2
  • 17
  • 34