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.

Abulurd
  • 1,018
  • 4
  • 15
  • 31
Leo
  • 835
  • 1
  • 12
  • 31
  • What's the real context of those last 3 lines? They cannot be sitting loose like that in real life... – matt Sep 29 '14 at 02:53
  • Well, that's the problem then. – matt Sep 29 '14 at 03:01
  • 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. – Paulw11 Sep 29 '14 at 03:05
  • 1
    JFI: it is working fine now on playground. – Bista Dec 21 '16 at 04:56

1 Answers1

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141