我在尝试使用UISearchBar从填充UITableView的数组中过滤对象时遇到错误。错误状态:Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2]'.
ViewController.m中的相关代码为:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if (isFiltered == YES)
{
NSLog (@"%i", indexPath.row);
cell.textLabel.text = [filteredCities objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = [initialCities objectAtIndex:indexPath.row];
}
return cell;
}
#pragma mark - UISearchBar Delegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if (searchText.length == 0)
{
isFiltered = NO;
}
else
{
isFiltered = YES;
filteredCities = [[NSMutableArray alloc] init];
for (NSString *cityName in initialCities)
{
NSRange cityNameRange = [cityName rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (cityNameRange.location != NSNotFound)
{
[filteredCities addObject:cityName];
}
}
}
[myTableView reloadData];
}
@end发布于 2013-09-18 07:38:35
您还应该将tableView:numberOfRowsInSection方法更改为如下所示:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (isFiltered) {
return [filteredCities count]; /// Filtered items
}
return [initialCities count]; /// All items
}发布于 2013-09-18 07:45:15
有一种更好的方法可以做到这一点。您应该使用搜索栏控制器。并使用这两个委托方法。
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:@"SELF.property contains[cd] %@",
searchText];
self.searchResults = [self.datasource filteredArrayUsingPredicate:resultPredicate];
}
// code to refresh the table with the users search criteria
// this gets called everytime the user search string changes.
// also it calls the function above.
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}现在位于您的表视图中。您可以通过以下语句引用搜索栏控制器创建的新表
self.searchBarController.searchResultsTable您可以将其放入if else中,然后检查以查看该表,而不是使用isFiltered属性。
if (tableView == self.searchDisplayController.searchResultsTableView){
} else { // your in the other original tablehttps://stackoverflow.com/questions/18860885
复制相似问题