Search code examples
swiftdynamicprotocolskey-value-observing

How to use KVO observe protocol's property?


Xcode shows the error Only members of classes may be dynamic when I try to add dynamic modifier to protocol's property.
So I tried in another way, add dynamic in class instead of in protocol, Gettable properties are must be indicated by writing {get}.
This is my code:

protocol.swift

var myproperty: Int {get} 

class.swift

dynamic var myproperty: Int {  
  return otherproperty  
}

If I observe myproperty in normal way, it will not triggers KVO notifications when otherproperty value changed, because myproperty value will not change before called or used.
Thanks a lot!


Solution

  • I think that we can use a little trick to achieve our goal. In protocol add a property named observeKeyPath Like this:

    protocol.swift

    var myproperty: Int {get} 
    var observeKeyPath: String {get}
    

    class.swift

    dynamic otherproperty: AnyObject!
    var myproperty: Int {  
      return otherproperty  
    }
    var observeKeyPath {
      return "otherproperty"
    }
    

    observe.swift

    self.addObserver(protocol, 
          forKeyPath: protocol.observeKeyPath, 
             options: .New | .Old, 
             context: nil)
    

    Tips: if keyPath using dot syntax like "object.property", make sure that object and property are all modified by dynamic.