[英]RACObserve for value update in NSMutableArray?
I'm having a problem reacting to a value change in NSMutableArray. 我在对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
. 这里的想法是在
NSMutableArray postedImagesIds
发生更改时调用uploadFields
。 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!! 然后就是更新值时,
RACObserve
永远不知道! Is there a way to recognize this change ? 有没有办法认识到这种变化?
Thanks in advance! 提前致谢!
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. 重要的部分是您必须通过KVC对
self
而不是对NSMutableArray对象的独立引用来执行NSMutableArray突变。 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. 这是因为
RACObserve()
建立的KVO相对于作为第一个参数传入的对象(在本例中为self
RACObserve()
是相对的,因此只有通过被观察对象的KVC兼容突变才会触发观察通知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.