Почему моя ссылка на UISearchTableView теряется после поиска, когда вызывается didSelectRowAtIndex

Мой поиск работает отлично и нормально при фильтрации, но после того, как я выбираю ячейку, indexPath параметра didSelectRowAtIndex indexPath всегда имеет значение null, а tableView, который передается в этот метод, всегда является UITableView вместо UISearchTableView, что означает обычно используемый if (tableView == self.searchDisplayController.searchResultsTableView) всегда возвращает false, даже если if (self.searchDisplayController.isActive) правильно возвращает true. Спасибо вам за любую помощь или совет.

Вот соответствующий код:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

if ([self.currentDrinkType.name isEqualToString:@"Beer"] || [self.currentDrinkType.name isEqualToString:@"Wine"] || [self.currentDrinkType.name isEqualToString:@"Liquor"] ){
    id  sectionInfo =
    [[_fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}else{
    if (tableView == self.searchDisplayController.searchResultsTableView){

        return [_searchResults count];
    }else{
        return [_drinks count];
    }
} }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"drink";
SWTableViewCell *cell = (SWTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Drink *drinkCell;

    if ([self.currentDrinkType.name isEqualToString:@"Beer"] || [self.currentDrinkType.name isEqualToString:@"Wine"] || [self.currentDrinkType.name isEqualToString:@"Liquor"] ){
    drinkCell = [_fetchedResultsController objectAtIndexPath:indexPath];
    }else{
        if (tableView == self.searchDisplayController.searchResultsTableView){
            drinkCell = [_searchResults objectAtIndex:indexPath.row];
        }else{
        drinkCell = [_drinks objectAtIndex:indexPath.row];
        }

}
   //Check if cell object has already been favorited, if it has render unfavorite button instead
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    NSString *favoriteText;
    if ([drinkCell.isFavorite boolValue]){
        favoriteText = @"Unfavorite";
    }else{
        favoriteText = @"Favorite";
    }
        [rightUtilityButtons sw_addUtilityButtonWithColor:
         [UIColor colorWithRed:0.78f green:0.78f blue:0.8f alpha:1.0]
                                                    title:favoriteText];


    //Can only delete a drink if it is custom
    if ([drinkCell.isCustom boolValue] && drinkCell.isCustom != nil){
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f]
                                                title:@"Delete"];

        [rightUtilityButtons sw_addUtilityButtonWithColor:
         [UIColor colorWithRed:0.231f green:0.231f blue:1.0f alpha:1.0f]
                                                    title:@"Edit"];

    }

    cell = [[SWTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                  reuseIdentifier:CellIdentifier
                              containingTableView:self.tableView // For row height and selection
                               leftUtilityButtons:nil
                              rightUtilityButtons:rightUtilityButtons];
    cell.delegate = self;


// Configure the cell...

[self configureCell:cell atIndexPath:indexPath tableView:tableView];

return cell;}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView {
Drink *drinkCell;
if ([self.currentDrinkType.name isEqualToString:@"Beer"] || [self.currentDrinkType.name isEqualToString:@"Wine"] || [self.currentDrinkType.name isEqualToString:@"Liquor"] ){
    drinkCell = [_fetchedResultsController objectAtIndexPath:indexPath];
}else{
    if (tableView == self.searchDisplayController.searchResultsTableView){

        drinkCell = [_searchResults objectAtIndex:indexPath.row];
    }else{
         drinkCell = [_drinks objectAtIndex:indexPath.row];
    }


}
cell.textLabel.text = drinkCell.name;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%%", drinkCell.alcoholByVolume];

}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
NSPredicate *resultPredicate;

if ([self.currentDrinkType.name isEqualToString:@"Beer"] || [self.currentDrinkType.name isEqualToString:@"Wine"] || [self.currentDrinkType.name isEqualToString:@"Liquor"]){
    resultPredicate= [NSPredicate predicateWithFormat:@"SELF.name contains[cd] %@ AND drinkType ==%@",searchText, self.currentDrinkType];
    [NSFetchedResultsController deleteCacheWithName:[NSString stringWithFormat:@"Root%@", self.currentDrinkType]];
    [_fetchedResultsController.fetchRequest setPredicate:resultPredicate];

    NSError *error = nil;
    if (![[self fetchedResultsController] performFetch:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

}else{
            resultPredicate= [NSPredicate predicateWithFormat:@"SELF.name contains[cd] %@",searchText];
    _searchResults = [[_drinks filteredArrayUsingPredicate:resultPredicate]mutableCopy];

}

}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{ 
[self filterContentForSearchText:searchString
                           scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                  objectAtIndex:[self.searchDisplayController.searchBar
                                                 selectedScopeButtonIndex]]];

return YES;}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

NSManagedObjectContext *context = [self managedObjectContext];
 Drink *theDrink;
if (tableView == self.searchDisplayController.searchResultsTableView){
NSLog(@"search index %@", [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow]);
}
selectedIndexPath = indexPath;
NSLog(@"selected index path %d", selectedIndexPath.row);
NSManagedObject *selectedDrink;
if ([self.currentDrinkType.name isEqualToString:@"Beer"] || [self.currentDrinkType.name isEqualToString:@"Wine"] || [self.currentDrinkType.name isEqualToString:@"Liquor"] ){
            theDrink = [_fetchedResultsController objectAtIndexPath:indexPath];
    selectedDrink = [_fetchedResultsController objectAtIndexPath:indexPath];

}else{
    if (self.searchDisplayController.isActive){
        selectedDrink = [_searchResults objectAtIndex:indexPath.row];
        theDrink = [_searchResults objectAtIndex:indexPath.row];
    }else{
       selectedDrink = [_drinks objectAtIndex:indexPath.row];
        theDrink = [_drinks objectAtIndex:indexPath.row];
    }

}


[selectedDrink setValue:[NSDate date] forKey:@"lastChosen"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);

}

self.selectedDrink = theDrink;
[self.delegateDrink drinkTableViewControllerDidFinish:self];

[self dismissViewControllerAnimated:YES completion:^{

}];

}


person zacattac50    schedule 05.04.2014    source источник


Ответы (1)


Методы делегата, начинающиеся с параметра экземпляра UITableView, должны различать обычное табличное представление и представление результатов поиска. Параметр пути к индексу соответствует табличному представлению (т. е. обычному или поисковому). Убедитесь, что вы получаете путь индекса, соответствующий ожидаемому табличному представлению.

person Jacob    schedule 06.04.2014
comment
Спасибо за ответ. Когда я вызываю if (tableView == self.searchDisplayController.searchResultsTableView){ NSLog(@search index %@, [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow]); } этот метод никогда не вызывается, даже если он вызывается в результатах поиска. Итак, я проверяю, в каком табличном представлении я нахожусь, проблема в том, что переданный tableView не является searchResultsTableView, каким он должен быть. - person zacattac50; 06.04.2014