简体   繁体   中英

Filtered KVO NSMutableArray for UITableView

I have a NSMutableArray when it is added to, removed from, or changes the notifications from the array update my UITableView such that those changes are reflected in the UITableView automatically using KVO observing. This works great.

We now a have a new requirement that we want to filter out certain items from the array. This just shows what kind of filtering I would like to do:

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

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

However, doing the above does not work, I can't create a new array because it is being monitored by the UITableView, and I want to preserve the fine grained notifications that we get from the insertions and removals from the model array rather than reloading the entire table when a change occurs. So what I need is a way to only get notifications from newly inserted or removed items from the model that also meet the criteria.

So what, I think, I really want is two arrays, one that is the model, and another is the filtered presentation array. The presentation array will register for KVO notifications with the model array. The UITableView will register for notifications on the filtered presentation array. So if the insertion occurs in the model array it will send notification to the presentation array, then I need to check if it meets the criteria before inserting it in the presentation array or if it does not, then ignore the insertion. The problem I having is getting this to work correctly, the order of the items in the model is important and must be preserved. Any help or suggestions for alternative approaches would be greatly appreciated.

you have to maintain the model array and combinate the notification with the new array. So for example:

@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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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