我正在为我的应用程序创建一个搜索功能,我想突出显示单元格中的搜索字符串。
为此,我将搜索字符串保存到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