ios 如何在 Swift 中调用 deinit

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26091862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:53:05  来源:igfitidea点击:

How to call deinit in Swift

iosswift

提问by Leo

I wrote a code block as the following:

我写了一个代码块如下:

class Person{
        let name:String;
        init(name:String){
         self.name = name;
          println("\(name) is being initialized.");
     }

     deinit{
         println("\(name) is being deInitialized.");

    }
 }

var person:Person?;
person = Person(name:"leo");
person = nil;

When initialized,printis ok. When set person to nil,the deinitmethod is not called.

初始化后,没问题print。将 person 设置为 时nildeinit不会调用该方法。

回答by matt

The problem is that a playground is not real life. This is just one more reason for not using them (I think they are a terrible mistake on Apple's part). Use a real iOS app project and deinitwill be called as expected.

问题是游乐场不是现实生活。这只是不使用它们的另一个原因(我认为它们是 Apple 的一个可怕的错误)。使用真正的 iOS 应用程序项目并将deinit按预期调用。

Example from a real project:

来自真实项目的示例:

class ViewController: UIViewController {
    class Person{
        let name:String;
        init(name:String){
            self.name = name;
            println("\(name) is being initialized.");
        }
        deinit{
            println("\(name) is being deInitialized.");

        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        var person:Person?;
        person = Person(name:"leo");
        person = nil;
    }
}

That does what you expect it to do.

这会做你期望它做的事情。