UITableView异步重载数据



我正在为我的应用程序制作一个搜索函数,我想在单元格中突出显示搜索字符串
为此,我将搜索字符串保存到tableView:cellForRowAtIndexPath可以访问的全局变量activeSearchString
tableView:cellForRowAtIndexPath然后在它将返回的单元格中高亮显示activeSearchString的内容。然而,它不起作用。如果您检查日志,看起来reloadData是异步执行的(因此在activeSearchString被释放之后)
因此,我的应用程序也会崩溃。。是否有执行reloadData同步或其他方法的解决方案?谢谢

代码:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(){
// Get the products asynchronous    
NSString* searchString = [NSString stringWithString:@"A search string"];
NSArray* searchResults = [[ProductServer sharedServer] productsForSearchString:searchString];
dispatch_sync(dispatch_get_main_queue(), ^(){
DLog(@"Begin");
activeSearchString = [searchString retain];
products = [searchResults retain];
[ibTableView reloadData];
[activeSearchString release];
DLog(@"End");
});
});
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
DLog();
ProductTableViewCell* tableViewCell = [tableView dequeueReusableCellWithIdentifier:@"productCell" forIndexPath:indexPath];
Product* product = [products objectAtIndex:[indexPath row]];
NSDictionary* highlightAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:49.f/255.f green:110.f/255.f blue:184.f/255.f alpha:1.f], NSBackgroundColorAttributeName, nil];
NSMutableAttributedString* mutableAttributedTitle = [[[NSMutableAttributedString alloc] initWithString:[product title]] autorelease];
[mutableAttributedTitle setAttributes:highlightAttributes range:[[mutableAttributedTitle string] rangeOfString:activeSearchString options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch]];
[(UILabel*)[tableViewCell titleLabel] setAttributedText:mutableAttributedTitle];
return tableViewCell;
}

日志:

2012-11-13 14:56:00.783 ****[5810:c07] __58-[TVCurrentlyViewController searchBarSearchButtonClicked:]_block_invoke_2 [Line 190] Begin
2012-11-13 14:56:00.783 ****[5810:c07] __58-[TVCurrentlyViewController searchBarSearchButtonClicked:]_block_invoke_2 [Line 197] End
2012-11-13 14:56:00.783 ****[5810:c07] -[TVCurrentlyViewController tableView:cellForRowAtIndexPath:] [Line 117] 
2012-11-13 14:56:00.786 ****[5810:c07] -[TVCurrentlyViewController tableView:cellForRowAtIndexPath:] [Line 117] 
2012-11-13 14:56:00.787 ****[5810:c07] -[TVCurrentlyViewController tableView:cellForRowAtIndexPath:] [Line 117] 
2012-11-13 14:56:00.789 ****[5810:c07] -[TVCurrentlyViewController tableView:cellForRowAtIndexPath:] [Line 117] 
2012-11-13 14:56:00.790 ****[5810:c07] *** -[CFString length]: message sent to deallocated instance 0x75d6d00

您不应该在那里发布全局。在视图控制器的dealloc方法中使用具有retain语义和release的合成属性。

编辑:

在对主线程的回调中使用dispatch_async()而不是dispatch_sync()dispatch_sync()将在主线程完成表视图更新时阻塞全局后台队列。

最新更新