Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call deinit in Swift [duplicate]

Tags:

ios

swift

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.

like image 329
Leo Avatar asked Sep 29 '14 02:09

Leo


People also ask

Why is Deinit not called?

If you return nil from a failable initializer, init?() , or if you throw an error from a throwing initializer, init() throws , then deinit will not get called. This means you must clean up any manually allocated memory or other resources before you return nil or throw .

What is deinit?

Deinitialization is a process to deallocate class instances when they're no longer needed. This frees up the memory space occupied by the system. We use the deinit keyword to create a deinitializer.


1 Answers

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.

like image 148
matt Avatar answered Oct 12 '22 14:10

matt