Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

memory management - Deinit method is never called - Swift playground

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.
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...