1

I'm having a problem reacting to a value change in NSMutableArray.

I have the following (somewhat simplified) code to detect a change:

[[RACObserve(self, postedImagesIds) filter:^BOOL(NSMutableArray * postedImagesIds) {
    return [postedImagesIds count] > 0;
}] subscribeNext:^(NSMutableArray * postedImagesIds) {
    [self uploadFields:fields];
}];

The idea here is to call uploadFields when there is a change in NSMutableArray postedImagesIds. But not only when a new element is added, but also when a value is updated like so:

[self.postedImagesIds replaceObjectAtIndex:i withObject:imagePosted.imagePostedId];

Then thing is that when the value is updated, RACObserve never knows!! Is there a way to recognize this change ?

Thanks in advance!

1 Answer 1

10

It can be done, sort of. The important part is that you must perform your NSMutableArray mutation via KVC on self, rather than on an independent reference to the NSMutableArray object. In other words, it won't work if you do this:

[self.postedImagesIds addObject:imagePosted.imagePostedId];
or
[self.postedImagesIds replaceObjectAtIndex:i withObject:imagePosted.imagePostedId];

instead, you must add or replace the object like this:

NSMutableArray *fromKVC = [self mutableArrayValueForKey:@"postedImagesIds"];
[fromKVC addObject:imagePosted.imagePostedId];
or
[fromKVC replaceObjectAtIndex:i withObject:imagePosted.imagePostedId];

This is because the KVO established by RACObserve() is relative to the object you pass in as its first parameter (self, in this case), so only KVC-compliant mutations that pass through the observed object will trigger the observation notifications.

2
  • Cool, I had read about this but didn't understand the reason. Now it's much more clear. I managed to get it working by observing a counter but this is much better. Thanks!
    – Andres C
    Aug 7, 2014 at 2:55
  • Yeah, of course! Sorry I didn't do it before. Just wanted to test it first :D
    – Andres C
    Aug 7, 2014 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.