ios – ReactiveCocoa rac_valuesForKeyPath在Swift中不起作用

前端之家收集整理的这篇文章主要介绍了ios – ReactiveCocoa rac_valuesForKeyPath在Swift中不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在我用 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>

任何线索如何解决问题?

解决方法

可观察性需要是动态的

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

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"
  }
}
原文链接:/iOS/327949.html

猜你在找的iOS相关文章