繁体   English   中英

如何使用KVO观察协议的属性?

[英]How to use KVO observe protocol's property?

Xcode显示错误Only members of classes may be dynamic当我尝试向协议的属性添加dynamic修饰符时, Only members of classes may be dynamic的。
所以我尝试了另一种方法,在类而不是协议中添加dynamic ,必须通过编写{get}来指示Gettable属性。
这是我的代码:

protocol.swift

var myproperty: Int {get} 

class.swift

dynamic var myproperty: Int {  
  return otherproperty  
}

如果我以正常方式观察myproperty ,则在更改其他otherproperty值时,它不会触发KVO通知,因为myproperty值在调用或使用之前不会更改。
非常感谢!

我认为您不能使协议属性动态化,而只能使类/结构动态化。

编辑:

您应该能够做的一件事是使您的类继承自NSObject,然后实现将调用KVO willChangeValueForKey和didChangeValueForKey方法的willSet和didSet方法。

在了解Dynamic属性之前,我使用Swift类进行了此操作,并且它起作用了。 它也应该对协议起作用,但是使它起作用的负担在实现该协议的类或扩展上。

我认为我们可以使用一些技巧来实现我们的目标。 protocol添加一个名为observeKeyPath的属性, observeKeyPath所示:

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)

提示:如果keyPath使用点语法(例如"object.property" ,请确保objectproperty都由dynamic修改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM