[英]Dynamic OneToMany ReactiveCocoa binding
I have something similar to the following structure in my code: 我的代码中有类似于以下结构的内容:
// 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
During execution, number of children in each Father member can change (in this case I recreate the whole NSArray) and
position of each Child can also change .
在执行期间, 每个父亲成员中子代的数量可以更改(在这种情况下,我将重新创建整个NSArray)
,每个
子代的
位置也可以更改 。
Does any elegant solution in ReactiveCocoa exist to map the dynamic number of children positions in the model to averagePositionOfChildren in FatherViewModel? ReactiveCocoa中是否存在任何优雅的解决方案,可以将模型中子位置的动态数量映射到FatherViewModel中的averagePositionOfChildren?
Yes, I can see you choose two strategies: 是的,我可以看到您选择两种策略:
1. Use properties 1.使用属性
Use a MutableProperty
for children
and then create a mapped property for averagePositionOfChildren
. 为
children
使用MutableProperty
,然后为averagePositionOfChildren
创建一个映射属性。
2. Use KVO 2.使用KVO
Alternatively, you can use KVO to watch changes in children
. 另外,您可以使用KVO观看
children
变化。 Ie, you can create a DynamicProperty
. 即,您可以创建一个
DynamicProperty
。
Note that both scenarios would force you to recreate the whole array, as you already noted. 请注意,正如您已经提到的,这两种情况都会迫使您重新创建整个阵列。
If anyone is interested, here follows my own solution: 如果有人感兴趣,请按照我自己的解决方案进行操作:
@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.