我正在尝试在我用
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" } }