2017-08-10 21 views
0

是否可以使用鍵值編碼來訪問對象的超類屬性?如何使用鍵值編碼訪問超類屬性?

我想是這樣的:

class Bar: Foo { 
    var shouldOverridePropertyOfFoo: Bool = false 

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

但是,我得到這個運行時錯誤:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: ' [<MyModule.Bar 0x2da2cf003e00> valueForUndefinedKey:] : this class is not key value coding-compliant for the key super .'

注:我想弄清楚how to override private method and call super in swift?

回答

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"