When should I use deinit?

后端 未结 6 1434
谎友^
谎友^ 2020-12-08 06:55

I came across a function called deinit() while reading The Swift Programming Language guide, but I\'m still wondering why and when we need to implement it since

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 07:10

    A deinitializer is called immediately before a class instance is deallocated. You write deinitializers with the deinit keyword, similar to how initializers are written with the init keyword. Deinitializers are only available on class types.Class definitions can have at most one deinitializer per class. The deinitializer does not take any parameters and is written without parentheses. I used deinit to removeObserver of notification from the application,as given below.

    deinit {
        NotificationCenter.default.removeObserver(self, name: 
        NSNotification.Name(rawValue: "gotoLogin"), object: nil)
        NotificationCenter.default.removeObserver(self, name: 
        NSNotification.Name(rawValue: "gotoMain"), object: nil)
        NotificationCenter.default.removeObserver(self, name: 
        NSNotification.Name(rawValue: "gotoRegister"), object: 
        nil)
        NotificationCenter.default.removeObserver(self, name: 
        NSNotification.Name(rawValue: "gotoBook"), object: nil)
        NotificationCenter.default.removeObserver(self, name: 
        NSNotification.Name(rawValue: "gotoCurrentMainMenu"), 
        object: nil)
        NotificationCenter.default.removeObserver(self, name: 
        NSNotification.Name(rawValue: "gotoEventMenu"), 
        object: nil)
    }
    

提交回复
热议问题