0

我的代码中有类似于以下结构的内容:

// Model
@interface Child : NSObject
@property (nonatomic, assign) CGPoint position;
@end

@interface Father : NSObject
@property (nonatomic, strong) NSArray <Child *> *children; // (0..n)
@end

// ViewModel
@interface FatherViewModel : NSObject
@property (nonatomic, strong) Father *father;
@property (nonatomic, assign) CGPoint averagePositionOfChildren;
@end

在执行期间,每个父亲成员中的孩子数量可以改变(在这种情况下我重新创建整个 NSArray),每个孩子的位置也可以改变

ReactiveCocoa 中是否存在任何优雅的解决方案来将模型中子位置的动态数量映射到 FatherViewModel 中的 averagePositionOfChildren?

4

2 回答 2

0

是的,我可以看到您选择了两种策略:

1.使用属性

使用MutablePropertyforchildren然后为 . 创建映射属性averagePositionOfChildren

2.使用KVO

或者,您可以使用 KVO 来观察children. 即,您可以创建一个DynamicProperty.

请注意,正如您已经指出的那样,这两种情况都会迫使您重新创建整个数组。

于 2017-05-28T14:15:59.067 回答
0

如果有人有兴趣,这里遵循我自己的解决方案:

@interface FatherViewModel()
@property (nonatomic, strong) RACDisposable *averageBindingDisposable;
@end

@implementation FatherViewModel
- (instanceType) init {
self = [super init];
...
...
RACSignal *signalOfSignals = [RACObserve(self, father.children)
                         map:^RACSignal *(NSArray <Child *> *setOfChildren) {
                             NSArray <RACSignal *> *arrayOfSignal = [[[setOfChildren rac_sequence]
                                                                      map:^RACSignal *(Child *child) {
                                                                          return RACObserve(child, position);
                                                                      }]
                                                                     array];
                             return [RACSignal combineLatest:arrayOfSignal];
                         }];

[self.averageBindingDisposable dispose];
self.averageBindingDisposable = [[[signalOfSignals flatten]
                  map:^NSValue *(RACTuple *tuple) {
                      NSArray <NSValue *> *arrayOfWrappedCGPoints = tuple.allObjects;
                      CGPoint avg = CGPointZero;
                      // Compute here the average of the points in the array
                      return [NSValue valueWithPoint: avg];
                  }]
                  setKeyPath:@"averagePositionOfChildren" onObject: self];
}];

return self;
}
...
@end
于 2017-12-29T09:06:20.097 回答