Question

How do I subscribe to objects being added and removed from a NSMutableDictionary using ReactiveCocoa? Also, I'd like to broadcast a notification when it changes. My guess is that broadcasting can be done using RACMulticastConnection but how do I tie this up with the dictionary change? I'm trying to use ReactiveCocoa for the first time in my project and stuck on the first thing I wanted to do :(

Was it helpful?

Solution

RACObserve is a wrapper around key-value observing, and inherits the same features and flaws.

Unfortunately, NSMutableDictionary is not automatically observable. There are two ways to work around that:

  1. Subclass it and add KVO support.
  2. Create a real model object, with properties instead of dictionary keys. Then you'll get KVO on those properties, as long as you use setters instead of direct ivar modification.

I'm not sure exactly what you mean by "[broadcasting] a notification when it changes," or why it'd be valuable. Notifications are way too global for my taste, and I'd promote using more limited observation instead (like KVO).

However, assuming you definitely want to do this, it's simple enough to post a notification in response to a new signal value:

@weakify(self);
[RACObserve(self, dictionary) subscribeNext:^(NSDictionary *dictionaryValue) {
    @strongify(self);
    [NSNotificationCenter.defaultCenter postNotificationName:SomeNotificationName object:self];
}];

If you want KVO's change dictionary (which includes information about the added/removed values), you'll need to replace RACObserve with +rac_valuesAndChangesForKeyPath:options:observer:.

OTHER TIPS

every time you set or remove the key-value,reset the dict,so you can observer the dict. just like:

 [RACObserve(self, testDict) subscribeNext:^(id x) {
     NSLog(@"RACObserve testDict:%@",x);
 }];

[self.testDict setObject:value forKey:key];
self.testDict=self.testDict;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top