gpt4 book ai didi

ios - 如何使用 grand central dispatch 过滤集合并在完成后更新 UITableView?

转载 作者:行者123 更新时间:2023-11-28 22:52:35 26 4
gpt4 key购买 nike

我正在尝试使用 grand central dispatch 过滤 NSArray。我能够过滤数组,当我调用 [tableView reloadData] 时,NSLog 正在打印正确的值;但是 View 显示以前的值。

例如,如果我的项目集合是 Red, Orange, Yellow 并且我过滤 r,NSLogs 将打印有 2 行并且单元格是RedOrange,但所有三个单元格都会显示。当搜索变为 ra 时,NSLog 显示只有 1 行名为 Orange,但单元格 RedOrange已显示;

- (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。是的,self 将在 block 运行时保留,但在 block 完成时将再次释放。如果这个对象真的可以在运行时消失,那么好吧,使用对 self 的弱引用。

您在本地和 block 中使用“items”作为名称,为了确定,我将局部变量名称更改为数组。

关于ios - 如何使用 grand central dispatch 过滤集合并在完成后更新 UITableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11583154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com