[英]How do I filter a collection with grand central dispatch and update a UITableView when done?
我正在尝试使用大中央调度来过滤NSArray。 我能够过滤数组,当我调用[tableView reloadData]
,NSLog正在打印正确的值; 但视图显示以前的值。
例如,如果我的项目集合是Red, Orange, Yellow
和我过滤r
,则NSLog将打印出有2行,单元格为Red
和Orange
,但是将显示所有三个单元格。 当搜索变为ra
,NSLog显示只有一行称为Orange
,但显示Red
和Orange
单元格;
- (void)filterItems:(NSString *)pattern{
__weak MYSearchViewController *weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableArray *items = [weakSelf.items copy];
//lots of code to filter the items
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.items = [items copy];
[weakSelf.tableView reloadData];
});
});
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(@"Rows: %d",[self.items count]);
return [self.items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"MYCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
NSInteger row = [indexPath row];
MYItem *item = [self.items objectAtIndex:row];
//code to setup cell
NSLog(@"Row %d, Item %@, Cell %d", row, item.info, cell.tag);
return cell;
}
尝试这个:
- (void)filterItems:(NSString *)pattern
{
NSMutableArray *array = [NSMutableArray arrayWithArray:items];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//lots of code to filter the items using "array", NOT items
dispatch_async(dispatch_get_main_queue(), ^{
items = array; // or [NSArray arrayWithArray:array] if you really don't want a mutable array
[tableView reloadData];
});
});
}
评论:你不需要使用自己。 是的,在块运行时将保留self,但是当块完成时它将再次释放。 如果这个对象在运行时真的可以消失,那么OK,使用弱引用自我。
您在本地使用“items”作为名称,在块中,我将局部变量名称更改为数组以确保。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.