问题
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:
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.
来源:https://stackoverflow.com/questions/25162893/racobserve-for-value-update-in-nsmutablearray