我正在尝试将searchBarController添加到我的tableView中。我在构建应用程序时没有遇到任何错误,但当我开始在searchBar中输入时,应用程序会抛出异常并崩溃。
导致崩溃的行在下面的最后一块代码中进行了注释。有人知道这里可能出了什么问题吗?非常感谢!
我的.h文件的相关部分:
@interface BusinessesViewController : UITableViewController<CLLocationManagerDelegate,
UISearchDisplayDelegate> {
IBOutlet UITableView *mainTableView;
NSArray *businesses;
NSMutableData *data;
NSArray *filteredBusinesses;
}
我的视图的相关部分DidLoad方法:
- (void)viewDidLoad {
filteredBusinesses = [[NSArray alloc]init];
}
行数选择方法:
- (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
中的对象具有"name"属性,因此谓词应该是
[NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", searchText]
^key ^operator ^value