Is it possible to observer a NSMutableArray from different class?

时间:2016-02-12 20:27:30

标签: ios objective-c mvvm nsmutablearray key-value-observing

I'll try to summarize this as succinctly as possible:

I have three classes: a ViewController, a ViewModel, and a DataSource.

The ViewController creates both the ViewModel and DataSource. It then proceeds to "configure" the DataSource with a NSMutableArray that was initially created by and is owned by the ViewModel.

I'm aware that by implementing the appropriate indexed accessor methods I can make the NSMutableArray property KVO compliant so that my ViewModel can observe its changes.

However, what I want to do is observe the changes from my DataSource.

When it is configured the DataSource, "sets" the NSMutableArray to its own "objects" property (weak, strong, copy???). Whenever the NSMutableArray is updated via the ViewModel (which does the fetching from the server), my ViewModel is made aware of the changes. But, I can't seem to be able to observe these changes from the DataSource.

Any suggestions?

(Also, not a priority, but does anyone know of a way to do this "reactively" with RAC?).

1 个答案:

答案 0 :(得分:1)

Yes, it's possible to observe changes to an array property of one class from another class. I've done it. It's been a long time, and I don't have the code at hand, so I can't give you specifics, but it is indeed possible.

It's fragile, since if the listening object gets deallocated without removing itself as a KVO observer, you crash.

This sort of KVO observation seems like bad mojo to me. It creates fairly tight coupling between your classes, and makes the observing class dependent on implementation details of the observed class.

If I were to do this again I would probably use KVO within the class that owns the array, and then broadcast a notification, use a callback, or use some other method to notify the interested external object about the change that does not have such tight coupling.

相关问题