如何观察价值的变化并显示出来? 在Swift中
我有一个variables,在一个不同的类中的数组中的对象的数量,我怎么能跟踪当前类中的这个variables的变化? 我做了很多不同的尝试,但都失败了。
var digitIndex: Int! { set { self.digitIndex = newValue } get { return firstClass.indexesOfSelectedNodes().count } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if context == &digitIndex { if let newValue = change?[NSKeyValueChangeNewKey] { print("newValue") infoLabel.text = "\(newValue)" } } }
1)在你的代码中
var digitIndex: Int! { set { self.digitIndex = newValue } get { return firstClass.indexesOfSelectedNodes().count } }
digitIndex是计算属性! 你不能在自己的setter中设置self.digitIndex!
这个代码,即使编译,将永远运行:-)
var i: Int { get { return 10 } set { i = newValue } } i = 100 print(i)
2)如何使用willSet和didSet(对于STORED属性)?
class C1 {} class C2 {} class C { var objects: [AnyObject] = [C1(),C1(),C2()] { willSet { print(objects, objects.count, newValue) } didSet { print(objects, objects.count) } } func add(object: AnyObject) { objects.append(object) } } let c = C() c.add(C1()) /* [C1, C1, C2] 3 [C1, C1, C2, C1] [C1, C1, C2, C1] 4 */ var i: Int = 0 { willSet { print(newValue, "will replace", i) } didSet { print(oldValue, "was replaced by", i) } } i = 100 /* 100 will replace 0 0 was replaced by 100 */
你可以结合计算和存储的属性为您的优势
// 'private' storage var _j:Int = 0 var j: Int { get { return _j } set { print(newValue) if newValue < 300 { _j = newValue } else { print(newValue, "refused") } } } print(j) // prints 0 j = 200 // prints 200 print(j) // prints 200 j = 500 // prints 500 refused print(j) // prints 200
尝试这个 :
var digitIndex: Int! { set { self.digitIndex = newValue } get { return firstClass.indexesOfSelectedNodes().count } didSet { //you will get new value here } }
无需为我们的类属性添加观察者,只需要为超类提供的属性添加观察者即可。
你可以使用一个委托来处理你的两个类之间的通信。
下面的示例使用自定义委托MyDelegate
(协议)。 一个委托实例在MyOtherClass
(例如一个视图控制器类)中被初始化,当这个类中的数组myArr
被更新的时候,这个委托会进行委托callback。 这反过来更新digitIndex
中的MyCurrentClass
的值(例如,一些自定义控件),它通过实现蓝图arrUpdated(..)
方法符合MyDelegate
。 最后, digitIndex
中的MyCurrentClass
上的didSet
属性观察者通过控制台打印告诉我们它的值已被更新。
protocol MyDelegate: class { func arrUpdated(arr: [Int]) } class MyDifferentClass { private var myArr : [Int] = [] { didSet { // Call delegate. delegate?.arrUpdated(myArr) } } weak var delegate: MyDelegate? } class MyCurrentClass: MyDelegate { var myDifferentClass : MyDifferentClass var digitIndex: Int = 0 { didSet { print("digitIndex updated: \(digitIndex)") } } init(a: MyDifferentClass) { myDifferentClass = a myDifferentClass.delegate = self } // MyDelegate func arrUpdated(arr: [Int]) { digitIndex = arr.count } }
testing:
var a = MyDifferentClass() var b = MyCurrentClass(a: a) a.myArr.append(1) // prints 'digitIndex updated: 1'