SearchBarController谓词导致崩溃
问题描述:
我想添加一个searchBarController到我的tableView中。当我构建应用程序时,我没有收到任何错误,但是当我开始在searchBar中输入内容时,该应用程序会引发异常并崩溃。SearchBarController谓词导致崩溃
导致崩溃的行在最后一段代码中注释如下。有人知道这里可能会出现什么问题吗?非常感谢!
我.h文件中的有关部分:
@interface BusinessesViewController : UITableViewController<CLLocationManagerDelegate,
UISearchDisplayDelegate> {
IBOutlet UITableView *mainTableView;
NSArray *businesses;
NSMutableData *data;
NSArray *filteredBusinesses;
}
我的viewDidLoad方法的主要部分:
- (void)viewDidLoad {
filteredBusinesses = [[NSArray alloc]init];
}
NumberOfRowsInSection方法:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredBusinesses count];
}
else {
return [businesses count];
}
}
的cellForRowAtIndexPath方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath {
BusinessesTableViewCell *cell = (BusinessesTableViewCell *)[tableView
dequeueReusableCellWithIdentifier:@"MainCell"];
if (tableView == self.searchDisplayController.searchResultsTableView) {
[cell.businessMainLabel setText:[[filteredBusinesses
objectAtIndex:indexPath.row]objectForKey:@"name"]];
}
else {
[cell.businessMainLabel setText:[[businesses
objectAtIndex:indexPath.row]objectForKey:@"name"]];
}
return cell;
}
谓词和SearchDisplayController方法:
- (void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"beginswith[cd] %@",
searchText];
//THIS LINE OF CODE CAUSES THE CRASH
filteredBusinesses = [businesses filteredArrayUsingPredicate:predicate];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:
[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
答
你的谓语是错误的,关键丢失。从其他代码,它看起来好像 在businesses
的对象有一个“名称”属性,所以谓语应该
[NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", searchText]
^key ^operator ^value
感谢马丁,我觉得我越来越接近这里。 name属性来自JSON响应,如下所示:'[[business objectAtIndex:indexPath.row] valueForKey:@“name”]'关于如何处理这个问题的任何想法? – Brandon 2014-08-28 08:49:49
@Brandon:然后上面的工作。 - 请注意,'valueForKey:'通常是错误的方法(它是用于键值编码的),上面的代码使用'objectForKey:'这是正确的。 – 2014-08-28 08:53:32
好的,谢谢,如果我输入一个确实在tableView中的字母,它现在只会崩溃。如果我输入的东西不在tableView数组中,它会适当地说“没有结果”,为什么这个问题仍然会崩溃? – Brandon 2014-08-28 08:57:40