Dipak
Dipak

Reputation: 2433

Deinit method is not called in Xcode 10 Beta 6 playground

I was exploring memory management concept and found deinit method is not calling in Xcode 10 beta 6 playground. Initially I thought may be some problem in code. Then I test same code in Xcode 9.4.1 playground and Xcode 10 beta 6 sample app everything is working as expected (deinit method is called). Is it bug in Xcode 10 beta 6 playground or anything else? I am using apple developer's code-

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

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

    deinit { print("\(name) is being deinitialized") }
}

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

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

do {
    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
}

Upvotes: 1

Views: 188

Answers (1)

Dario JG
Dario JG

Reputation: 67

This issue seems to still be present in Xcode 10.0 (10A255). I have playground with the following code:

class Person {
    var name: String

    func buy(car: Car) {
        car.owner = self
    }

    init(name: String) {
        self.name = name
        print("Person \(name) is initalized")
    }

    deinit {
        print("Person \(name) is being deinitialized")
    }
}


class Car {
    let model: String
    weak var owner: Person?

    init(model: String) {
        self.model = model
        print("Car \(model) is initialized")
    }

    deinit {
        print("Car \(model) is being deinitialized")
    }
}

print("===== before do =====")
do {
    print("    ---- do begin -----")
    let johnny = Person(name: "John")
    let porsche = Car(model: "Carrera4")
    johnny.buy(car: porsche)
    print("    ---- do end -----")
}
print("===== after do =====")

In Xcode 9.4.1 both Car's and Person's deinit are executed, but in Xcode 10.0 (10A255) the Person's deinit method is not executed.

The same code inside a test macOS project works as expected (both deinit executed) in Xcode 9.4.1 as well as Xcode 10.0 (10A255)

Upvotes: 2

Related Questions