22

In the next code I'm trying to call the deinit method releasing all the references to the Person Class instance Mark but the deinit is never called. Why?

class Person{

    let name:String

    init(name:String){
        self.name = name
        println("Person created")
    }

    deinit {

        println("Person \(name) deinit")
    }
}

var Mark:Person? = Person(name:"Mark")
Mark = nil // Shouldn't the person deinit method be called here? It doesn't.
mfaani
  • 33,269
  • 19
  • 164
  • 293
MatterGoal
  • 16,038
  • 19
  • 109
  • 186

5 Answers5

26

Xcode's Playgrounds for Swift don't work like regular apps; they aren't being run just once. The objects created stay in memory and can be inspected until you change the code, at which point the whole playground is reevaluated. When this happens, all previous results are discarded and while all object will be deallocated, you won't see any output from that.

Your code is correct, but Playgrounds is not suited to test things related to memory management.

Here's a related SO question: Memory leaks in the swift playground / deinit{} not called consistently

Community
  • 1
  • 1
Andreas Ley
  • 9,109
  • 1
  • 47
  • 57
6

Deinit will called if create object like this

_ = Person(name:"Mark")
Pardeep Bishnoi
  • 161
  • 1
  • 7
0

Deinit gets called when you ignore the variable like so.

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
_ = Owner()
PlaygroundPage.current.finishExecution()

Owner class -

public class Owner {
    public var car: Car?
    public init (_ car: Car? = nil) {
        self.car = car
        print ("Owner got allocated")
    }

    deinit {
        print ("owner got deallocated")
    }
}

// Prints - Owner got allocated owner got deallocated

nikhil
  • 1
  • 2
0

workaround - move all variable initialisation code into a function and call that function.

Kiran S
  • 403
  • 8
  • 13
-1

Playground having issues used to be a problem. For 99% of the memory management cases they work just like a normal project. Playground has improved A LOT over time.

Such a problem should no longer exist and Playground can be used reliably.

mfaani
  • 33,269
  • 19
  • 164
  • 293