ReactiveCocoa rac_valuesForKeyPath在Swift中不起作用

时间:2014-10-01 11:54:52

标签: ios swift reactive-cocoa

我试图在我用Swift编写的iOS应用程序中采用ReactiveCocoa。不幸的是,看起来rac_valuesForKeyPath没有按预期工作。 这是一个例子:

class Source: NSObject {
    var observable: String = "<Original>"

    override init() {
        super.init()

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.observable = "<Updated>"
            println("Updated value to \(self.observable)");
        })
    }
}

class Observer: NSObject {
    init(source: Source) {
        super.init()

        source.rac_valuesForKeyPath("observable", observer: self).subscribeNext { (value: AnyObject!) -> Void in
            println(">>> Observable value changed: \(value)")
        }
    }
}

该示例生成以下输出:

>>> Observable value changed: <Original>
Updated value to <Updated>

这意味着没有调用subcribeNext块。

预期输入为:

>>> Observable value changed: <Original>
Updated value to <Updated>
>>> Observable value changed: <Updated>

有任何线索如何解决问题?

1 个答案:

答案 0 :(得分:9)

可观察性需要是动态的

我让您的示例使用以下代码

class Source: NSObject {
  dynamic var string:String = "Initial Value"

  override init() {
    super.init()
  }
}

class Observer: NSObject {

  init(source:Source) {
    super.init()
    source.rac_valuesForKeyPath("string", observer: self).subscribeNext { (newVal:AnyObject!) -> Void in
      println(newVal)
    }
  }
}

class ViewController: UIViewController {
  var source:Source!
  var obs:Observer!

  override func viewDidLoad() {
    super.viewDidLoad()
    source = Source()
    obs = Observer(source: source)
    source.string = "Another Value"
  }
}