2014-02-13 32 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:...'不起作用。 –

相關問題