我正在爲我的應用程序搜索功能,我想突出顯示單元格中的搜索字符串。
爲此,我將搜索字符串保存到可由tableView:cellForRowAtIndexPath
訪問的全局變量activeSearchString
。
tableView:cellForRowAtIndexPath
然後在它將返回的單元格中突出顯示activeSearchString
的內容。 但是,它不起作用。如果你檢查日誌,看起來reloadData是異步執行的(所以在activeSearchString
被釋放後)。
因此,我的應用程序也崩潰..任何解決方案執行reloadData
同步或另一種方法?謝謝!UITableView 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
爲你的'tableView:cellForRowAtIndexPath'方法添加代碼。 – MusiGenesis