RACObserve for value update in NSMutableArray?

╄→尐↘猪︶ㄣ 提交于 2019-12-23 02:25:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!