2014-02-13 34 views
1

比方说,我有一个ColorListViewModel,其型号为彩色对象的数组:如何确保NSArray始终使用ReactiveCocoa进行排序?

@property (nonatomic, copy) NSArray *colors; 

,我更新是在执行命令整个模型:同时还具有一个addColor:方法

RAC(self, colors) = [_fetchColorsCommand.executionSignals flatten]; 

它具有以下功能:

- (void)addColor:(Color *)color 
{ 
    NSMutableArray *mutableColors = [self.colors mutablecopy]; 
    [mutableColors addObject:color]; 
    self.colors = [mutableColors copy]; 
} 

我可以在多个地方对颜色数组(例如名称)进行排序usi ng NSSortDescriptor。

如何订阅对self.colors的更改并在那里执行排序?到目前为止,我试图做到这一点导致了无限循环。

回答

0

,如果你做更多的插入或更多的阅读以及它取决于...

,如果你做了很多插入,而不是大量的阅读,那么你可以排序懒洋洋...... 这两个例子要求你定义-(NSComparisonResult)compareColor:(id)someOtherColor ... 你也可以使用块或函数。

- (NSArray *)colors 
{ 
    return [_colors sortedArrayUsingSelector:@selector(compareColor:) ]; 
} 

或者你可以排序在前场插入,如果你看了更频繁

- (void)addColor:(Color *)color 
{ 
    NSMutableArray *mutableColors = [self.colors mutablecopy]; 
    [mutableColors addObject:color]; 
    self.colors = [mutableColors sortedArrayUsingSelector:@selector(compareColor:)]; 
} 
1

看来,distinctUntilChanged是我失踪,防止无限循环。

[[RACObserve(self, colors) distinctUntilChanged] subscribeNext:^(NSArray *colors) { 
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)]; 
    self.colors = [colors sortedArrayUsingDescriptors:@[sortDescriptor]]; 
}]; 

这似乎工作,虽然我没有意识到在这一点上的任何警告。

+0

根据[这个答案](http://stackoverflow.com/a/19673276/339925)多次绑定到相同的属性是不是一个好主意。 这就是为什么我的答案写成'RAC(self,colors)= [[RACObserve(self,colors)distinctUntilChanged] map:...'不起作用。 –

相关问题