ios - 为 UITableView 过滤的 KVO NSMutableArray

标签 ios iphone objective-c uitableview key-value-observing

我有一个 NSMutableArray,当它被添加到、删除或更改数组中的通知时,会更新我的 UITableView,这样这些更改就会使用 KVO 观察自动反射(reflect)在 UITableView 中。这很好用。

我们现在有一个新要求,我们要从数组中过滤掉某些项目。这只是显示我想做什么样的过滤:

NSIndexSet *indexes = [array indexesOfObjectsPassingTest:
                       ^BOOL(MyObject *obj, NSUInteger idx, BOOL *stop)
                       {
                           return !obj.isHidden;
                       }];

NSMutableArray *newArray = [[array objectsAtIndexes:indexes] mutableCopy];

但是,执行上述操作不起作用,我无法创建一个新数组,因为它正在由 UITableView 监视,并且我想保留我们从模型数组的插入和删除而不是重新加载中获得的细粒度通知发生更改时的整个表。因此,我需要一种仅从模型中新插入或删除的也符合条件的项目中获取通知的方法。

那么,我想,我真正想要的是两个数组,一个是模型,另一个是过滤后的表示数组。演示数组将使用模型数组注册 KVO 通知。 UITableView 将在过滤的表示数组上注册通知。因此,如果插入发生在模型数组中,它将向表示数组发送通知,那么我需要在将其插入表示数组之前检查它是否符合条件,或者如果不符合,则忽略插入。我遇到的问题是让它正常工作,模型中项目的顺序很重要,必须保留。对于替代方法的任何帮助或建议将不胜感激。

最佳答案

您必须维护模型数组并将通知与新数组结合起来。例如:

@property (nonatomic, strong) NSArray *modelArray;
//This array is also initialized obviously

@property (nonatomic, strong) NSArray *filteredArray;
//On this array you put the array filtered and connect this with the notification.
//So you can start each time from the model array and set the filtered array (and so 
//change automatically the tableView).

关于ios - 为 UITableView 过滤的 KVO NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21492939/

相关文章:

ios - 我怎样才能得到没有分隔符的格式化小时字符串?

iphone - NSString 格式问题

ios - Xcode 8.1 在完成 block 上崩溃

iphone - 将目录内容复制到NSArray

css - 视频在 ipad 和 iphone (safari) 中无法以正确的宽度显示

ios动画。嵌套动画如何影响持续时间?

objective-c - 如何在 iOS < 4 中停止 UIView 动画

ios - 选择标记时 Google-Maps-iOS-SDK 崩溃

iphone - MKMapView 已最大化,但我不想要它

iphone - AVAudioPlayer 有问题吗?制造延迟