В основном я пытаюсь добавить функцию поиска в свое приложение для iPhone, но сейчас мне не очень везет. Я загрузил предоставленное Apple приложение Table Search и скопировал код в мой. Он строит нормально, но вот проблема. В отличие от примера Apple, все мои данные хранятся в массиве, доступ к которому осуществляется с помощью вызова [ciParser.currentArray].
Есть идеи, как изменить код в соответствии с моими потребностями? Я получаю сообщение об ошибке «Завершение приложения из-за необработанного исключения« NSRangeException », причина:« *** - [NSCFArray objectAtIndex:]: index (0) за пределами (0) »» каждый раз, когда я нажимаю на панели поиска и приложение выходит. Ниже приведен, в частности, код, который отладчик выделяет как проблемный.
Очевидно, эта ошибка означает, что база данных, в которой выполняется поиск, пуста, но я могу ошибаться.
FYI мое приложение загружает и анализирует RSS-канал, используя класс, на который ссылается ciParser - который, в свою очередь, сохраняет загруженный контент в массиве, который мне нужен для поиска.
Обновление: теперь кажется, что моя таблица не обновляется, когда находит информацию. Вот мой код, который должен это делать. Есть идеи? Благодаря.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
// Return YES to cause the search result table view to be reloaded.
Код для разбора:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
/*
If the requesting table view is the search display controller's table view, configure the cell using the filtered content, otherwise use the main list.
*/
CurrentItem * nextCurrentItem=[ciParser.currentArray objectAtIndex:indexPath.row];
if (tableView == self.searchDisplayController.searchResultsTableView)
{
// **(Code which debugger points to as being wrong)**
nextCurrentItem = [self.filteredListContent objectAtIndex:indexPath.row];
}
else
{
nextCurrentItem = [ciParser.currentArray objectAtIndex:indexPath.row];
}
NSString*settingValue = [[NSUserDefaults standardUserDefaults]stringForKey:@"state"];
if ([settingValue isEqualToString:@"New South Wales"]) {
cell.textLabel.text=nextCurrentItem.title;
}
else if ([settingValue isEqualToString:@"Western Australia"]) {
cell.textLabel.text=@"The FESA does not provide any Current Incident reports.";
}
else if ([settingValue isEqualToString:@"Victoria"]) {
cell.textLabel.text=nextCurrentItem.title;
}
else if ([settingValue isEqualToString:@"South Australia"]) {
cell.textLabel.text=nextCurrentItem.title;
}
else if ([settingValue isEqualToString:@"Tasmania"]) {
cell.textLabel.text=nextCurrentItem.title;
}
// Set up the cell...
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
Обновление: Это раздел, который я не считаю правильным, так как мои результаты поиска теперь отображаются пустыми, независимо от того, что я печатаю.
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
/*
Update the filtered array based on the search text and scope.
*/
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
/*
Search the main list for products whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array.
*/
//**This part threw many errors and I eventually got it to this but I suspect this is my problem.**
for (currentItem in ciParser.currentArray)
{
if ([scope isEqualToString:@"All"] || [currentItem.title isEqualToString:scope])
{
NSComparisonResult result = [currentItem.title compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[self.filteredListContent addObject:currentItem];
}
}
}
}