简体   繁体   English

如何在RxSwift中观察数组属性的变化

[英]How to observe array property changes in RxSwift

Here is my class: 这是我的班级:

class ViewController: UIViewController {
   var myArray : NSArray!
} 

I want to fire an event every time myArray points to a new array, like this: 我想每次myArray指向一个新数组时触发一个事件,如下所示:

self.myArray = ["a"]

self.myArray = ["b"]

I've tried rx_observe but failed, here is my code: 我试过rx_observe但失败了,这是我的代码:

self.rx_observe(NSArray.self, "myArray").subscribeNext { (array) -> Void in
   print(array)
}

It only fires the first time, what's the problem? 它只是第一次发射,有什么问题?

Most of the time, if you have control of the backing variable, you would prefer Variable to using rx_observe . 大多数情况下,如果您控制了支持变量,则首选使用Variable来使用rx_observe

class ViewController: UIViewController {
   var myArray : Variable<NSArray>!
}

The first time you'll use myArray, you would asign it like so 你第一次使用myArray时,你会这样做

myArray = Variable(["a"])

Then, if you want to change its value 然后,如果你想改变它的价值

myArray.value = ["b"]

And you can easily observe its changes, using 您可以使用,轻松观察其变化

myArray.asObservable().subscribeNext { value in
  // ...
}

If you really want to use rx_observe (maybe because the variable is used elsewhere in your program and you don't want to change the API of your view controller), you would need to declare myArray as dynamic (another requirement is that the hosting class is a child of NSObject , here UIViewController satisfies this requirement). 如果你真的想使用rx_observe (可能是因为变量在程序的其他地方使用而你不想更改视图控制器的API),你需要将myArray声明为dynamic (另一个要求是托管类)是NSObject的孩子,这里UIViewController满足这个要求)。 KVO is not implemented by default in swift, and using dynamic ensures access is done using the objective-c runtime, where KVO events are handled. 默认情况下,未在swift中实现KVO,并且使用dynamic确保使用objective-c运行时完成访问,其中处理KVO事件。

class ViewController: UIViewController {
  dynamic var myArray: NSArray!
}

Documentation for this can be found here 有关此文档可在此处找到

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

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