如何使用键值编码访问超类属性?

时间:2017-08-10 11:54:33

标签: swift super key-value-coding

是否可以使用键值编码访问对象的超类属性?

我试过这样的事情:

class Bar: Foo {
    var shouldOverridePropertyOfFoo: Bool = false

    var propertyOfFoo: String {
        if shouldOverrideProperty {
            return "property of Bar"
        } else {
            return value(forKeyPath: "super.propertyOfFoo") as! String
        }
    }
}

但是,我收到了这个运行时错误:

  

***由于未捕获的异常终止应用&#39; NSUnknownKeyException&#39;,原因:&#39; [<MyModule.Bar 0x2da2cf003e00> valueForUndefinedKey:]:此类与密钥super不符合键值编码。&#39;

注意:我试图找出how to override private method and call super in swift?

1 个答案:

答案 0 :(得分:1)

而不是super.aPropertyOfFoo,您必须使用Foo.aPropertyOfFoo,最好使用#keyPath代替Strings

class Foo: NSObject {
    @objc var aPropertyOfFoo = "property of foo"
}

class Bar: Foo {
    var shouldOverridePropertyOfFoo: Bool = false

    var propertyOfFoo: String {
        if shouldOverridePropertyOfFoo {
            return "property of bar"
        } else {
            return value(forKeyPath: #keyPath(Foo.aPropertyOfFoo)) as! String
        }
    }
}

let bar = Bar()
print(bar.propertyOfFoo) // "property of foo"