1

我正在为我的应用程序创建一个搜索功能,我想突出显示单元格中的搜索字符串。
为此,我将搜索字符串保存到activeSearchString可由tableView:cellForRowAtIndexPath.
tableView:cellForRowAtIndexPath然后突出显示activeSearchString它将返回的单元格中的内容。但是,它不起作用。如果您检查日志,似乎 reloadData 是异步执行的(所以 afteractiveSearchString已被释放)。
正因为如此,我的应用程序也崩溃了。任何执行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
4

1 回答 1

4

你不应该在那里发布一个全局变量。在视图控制器的 dealloc 方法中使用具有保留语义和释放的合成属性。

编辑:

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

于 2012-11-13T14:38:36.677 回答