从不调用 Deinit 方法 - Swift Playground [英] Deinit method is never called - Swift playground

查看:35
本文介绍了从不调用 Deinit 方法 - Swift Playground的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下一个代码中,我试图调用 deinit 方法,释放对 Person Class 实例 Mark 的所有引用,但从未调用 deinit.为什么?

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.

推荐答案

Xcode 的 Playgrounds for Swift 不像普通应用那样工作;它们不会只运行一次.创建的对象保留在内存中并且可以被检查,直到您更改代码,此时整个操场被重新评估.发生这种情况时,所有先前的结果都将被丢弃,而所有对象都将被释放,但您将看不到任何输出.

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.

您的代码是正确的,但 Playgrounds 不适合测试与内存管理相关的内容.

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

这是一个相关的 SO 问题:内存泄漏Swift Playground/deinit{} 未一致调用

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

这篇关于从不调用 Deinit 方法 - Swift Playground的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆