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:
var myproperty: Int {get}
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!
I think that we can use a little trick to achieve our goal. In protocol
add a property named observeKeyPath
Like this:
var myproperty: Int {get}
var observeKeyPath: String {get}
dynamic otherproperty: AnyObject!
var myproperty: Int {
return otherproperty
}
var observeKeyPath {
return "otherproperty"
}
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
.