为什么继承变量没有在swift中初始化?

时间:2016-10-07 10:39:17

标签: ios swift inheritance

我有一个名为RootViewController的主要UIViewController为

import UIKit
class RootViewController: UIViewController {
    var amIaccessible: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

和2个子控件名为oneViewController,twoViewController继承RootViewController为:(也读我的评论)

import UIKit
class oneViewController: RootViewController {
    var amIaccessible: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        amIaccessible = true // I have initialized this variable of RootViewController 
    }
}
import UIKit
class twoViewController: RootViewController {
    var amIaccessible: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        print(amIaccessible) // it should print true as initialized in oneViewController but its printing false :(
    }
}

现在的问题是我的oneViewController是我的应用程序的初始视图,而twoViewController是在第一个视图之后初始化的第二个视图,所以我希望RootViewController成为我的单例类型控制器,它可以在整个应用程序生命周期中保存我的变量和方法。我怎么能做到这一点?

我不需要像单独的单例类那样的解决方案,我知道这样做也可以创建一个可以在应用程序执行期间保存变量的共享实例。 所以请使用继承关系给我解决方案

2 个答案:

答案 0 :(得分:0)

以下是您应该了解的一些内容

class oneViewController: RootViewController {
var amIaccessible: Bool = false // here you are overridding the amIaccessible property. so if you will use this with oneViewController object it will always gives you overridden property value

override func viewDidLoad() {
    super.viewDidLoad()
    amIaccessible = true // here you are changing the overridden amIaccessible property value. if you want to change super class propert value you should use super keyword.
    print(self.amIaccessible) // true
    print(super.amIaccessible) // false


   // for e.g  super.amIaccessible = true // in the same way access it with super keyword.
 }
}

如果在twoViewController中如果要访问RootViewController的amIaccessible属性,则必须使用super with property,如果从oneViewController更改amIaccessible属性的值,则可以' t在twoViewController中得到相同的值,因为对于每个对象,iOS都会创建新属性,并在从内存中释放时终止它们。

class twoViewController: RootViewController {
var amIaccessible: Bool = false

override func viewDidLoad() {
    super.viewDidLoad()
    print(super.amIaccessible) // it will always gives you false
}

}

答案 1 :(得分:0)

我已经弄清楚了,要在其他viewcontrollers中访问RootViewController变量,那么我应该将它们设为静态,如:

once the database gets huge enough, migrations with defaults runs slow and may throw database timeout errors

以rootViewController.amIaccessible

访问父类的amIaccessible
import UIKit
class RootViewController: UIViewController {
    static var amIaccessible: Bool = false  // make this static

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}
相关问题