需求描述
我有一个父类(super class),它有一个 bool 变量,我想在子类之间共享它(通过引用传递)。 但是当我在 firstClass 中更改 sharedVariable 时,它不会为 secondClass 更改它。
Class parentClass: UIViewController {
var sharedVariable: Bool = false
}
Class firstChild: parentClass {
@IBAction func myButtonTouched(_ sender: Any) {
sharedVariable = true
}
}
Class secondChild: parentClass {
print(sharedVariable)
}
实现方式
声明一个静态变量,对静态变量进行确保对象的地址唯一。
class ParentClass: UIViewController {
static var sharedVariable: Bool = false
}
class FirstChild: ParentClass {
@IBAction func myButtonTouched(_ sender: Any) {
ParentClass.sharedVariable = true
}
}
class SecondChild: ParentClass {
func test() {
print(ParentClass.sharedVariable)
}
}