可以在Swift中覆盖deinit吗?

时间:2016-10-28 11:52:50

标签: ios swift memory-management swift3 deinit

从另一个类创建子类时,需要override init()函数,但不能覆盖deinit'函数'。

这在Swift中是否可行?

这是一个例子

class Foo {
    init(){
        print("Foo created")
    }

    deinit {
        print("Foo gone")
    }
}


class Bar: Foo {

    override init(){
        print("Bar created")
    }

    //Is not overwritten here
    deinit {
        print("Bar gone")
    }
}

内部示例viewcontroller

override func viewDidLoad() {
    super.viewDidLoad()

    var f: Foo?
    f = Foo()
    f = Bar()
    f = nil

}

输出

Foo created    //Foo object initialised - Foo init() called
Foo created    //Foo init() called before calling Bar init()? no call to superclass though..
Bar created    //Bar object initialised - Bar init() called
Foo gone       //Foo deinit called as Foo instance replaced by Bar instance
Bar gone       //Bar deinit called as Bar instance holds no references and is destroyed 
Foo gone       //Foo deinit called again as part of Bar object destruction?

添加到关于扩展deinit的原始问题:

在示例代码中,覆盖init()似乎会导致调用超类的init()函数。这是发生了什么事吗?

Bar实例取消初始化时会发生相同的行为。这也是这里发生的事情吗?

1 个答案:

答案 0 :(得分:8)

Description: Creates a new application at the provided path. The application name and package ID can also be customized. These values are set in the app manifest (config.xml) and are used when creating a native project (platforms/<platform>/). The application can be created from an existing template as well. You can use any template that is published on npm, in your local file path, or available from a git URL. PhoneGap also recommends a few popular templates and provides shortened names for each. You can list the recommended templates with the `template list` command. The [config] option allows you to pass a JSON string, which will be injected into `<path>/.cordova/config.json`. Options: --name, -n <name> application name (default: "Hello World") --id, -i <package> package name (default: "com.phonegap.hello-world") --copy-from, -src <path> create project using a copy of an existing project --link-to <path> symlink/shortcut to the www assets without copying --template <npm package|path|git url> create app using template found on npm, your local path, or a git URL. Examples: $ phonegap create path/to/my-app $ phonegap create path/to/my-app "com.example.app" "My App" $ phonegap create path/to/my-app --id "com.example.app" --name "My App" $ phonegap create path/to/my-app --copy-from ../my-other-app $ phonegap create path/to/my-app --template hello-world $ phonegap create path/to/my-app --template phonegap-template-hello-world Also See: $ phonegap help template $ phonegap help template list 不是常规方法,不能覆盖。每个实例都有一个独立的 deinit处理程序用于其类及其所有超类。

  

在实例解除分配之前,会自动调用取消初始化。您不能自己致电deinitializer。超类deinitializers由其子类继承,超类deinitializer在子类deinitializer实现的末尾自动调用。即使子类不提供自己的取消初始化,也总是调用超类deinitializers。

绝对没有理由改变超类在其deinit中所做的任何事情。

为什么它与deinit不同?在初始化程序中,您需要传递参数,还需要控制执行顺序(init之前的某些代码,super.init(...)之后的某些代码)。取消初始化是一个具有已定义执行顺序的自动过程。覆盖只会引入不必要的问题。