简体   繁体   English

如何使用ReactiveCocoa确保始终对NSArray进行排序?

[英]How can I make sure that an NSArray is always sorted, using ReactiveCocoa?

Let's say that I have a ColorListViewModel whose model is an array of Color objects: 假设我有一个ColorListViewModel,其模型是Color对象的数组:

@property (nonatomic, copy) NSArray *colors;

and I update the entire model when a command is executed: 当执行命令时,我会更新整个模型:

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

while also having an addColor: method which does the following: 同时还有一个addColor:方法,该方法可以执行以下操作:

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

I could sort the array of colors (by name, for example) in multiple places using NSSortDescriptor. 我可以使用NSSortDescriptor在多个位置对颜色数组进行排序(例如,按名称)。

How can I subscribe to changes to self.colors and perform the sorting there? 如何订阅对self.colors更改并在那里进行排序? So far my attempts to do this have resulted in an infinite loop. 到目前为止,我这样做的尝试导致了无限循环。

It appears that distinctUntilChanged was what I was missing to prevent the infinite loop. 似乎是我想防止无限循环所需要的distinctUntilChanged

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

This appears to be working although I'm not aware of any caveats at this point. 尽管我现在还没有发现任何警告,但这似乎是可行的。

well it depends on if you do more inserting or more reading... 好吧,这取决于您是否进行更多插入或更多阅读...

if you do a lot of inserting and not a lot of reading, then you could sort lazily... both of these examples require you to define -(NSComparisonResult)compareColor:(id)someOtherColor ... you could also use a block or function. 如果您进行了大量插入操作而又没有大量阅读内容,那么您可以懒惰地排序...这两个示例都需要您定义-(NSComparisonResult)compareColor:(id)someOtherColor ...,您也可以使用代码块或功能。

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

or you could sort up front on insert, if you read more frequently 或者,如果您阅读得更频繁,则可以在插入时进行排序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM