我正在尝试将searchBarController添加到我的tableView中。我在构建应用程序时没有收到任何错误,但是当我开始在searchBar中输入时,应用程序会抛出异常并崩溃。
导致崩溃的行在最后一段代码中注释如下。有谁知道这里可能出了什么问题?非常感谢!
我的.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;
}
Predicate和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;
}
答案 0 :(得分:1)
您的谓词错误,键缺失。从其他代码看起来好像
businesses
中的对象具有&#34;名称&#34;属性,所以谓词应该是
[NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", searchText]
^key ^operator ^value