How to call deinit in Swift [duplicate]
Asked Answered
E

1

19

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,print is ok. When set person to nil,the deinit method is not called.

Eneidaenema answered 29/9, 2014 at 2:51 Comment(4)
What's the real context of those last 3 lines? They cannot be sitting loose like that in real life...Plicate
Well, that's the problem then.Plicate
If you are trying this in a Playground, then I think that is why it isn't working. I just implemented the 'bank' example from the Swift book and in a playground the deinit method isn't called, but if I put the code into an application and run it, it is.Tyndale
JFI: it is working fine now on playground.Deflagrate
P
19

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 deinit will be called as expected.

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.

Plicate answered 29/9, 2014 at 3:2 Comment(4)
do you still "think they are a terrible mistake on Apple's part"Gessner
@Gessner no, now I think they are the work of the devilPlicate
semicolons(;), is it really required?Unconstitutional
@Unconstitutional They are the OP's semicolons. I'm just showing that the OP's code, as given, does work, if you put it in the right place.Plicate

© 2022 - 2024 — McMap. All rights reserved.