Change NSFetchedResultsController on SegmentedControl change

前端 未结 1 2027
清酒与你
清酒与你 2020-12-15 14:00

I\'ve got a UITableView which is filled using a Core Data NSFetchedResultsController. I\'ve now added a UISegmentedControl to the view

相关标签:
1条回答
  • 2020-12-15 14:29

    You could add another instance variable that represents the currently selected NSFetchedResultsController. And when the UISegmentedControl changes update this ivar.

    this could be the action that is triggered by the valuechange event of the segment

    - (IBAction *)segmentChanged:(UISegmentedControl *)sender {
        if ([sender selectedSegmentIndex] == 0) {
            self.currentFetchedResultsController = self.nsfrc1;
            [self.tableView reloadData];
        }
        else if ([sender selectedSegmentIndex] == 1) {
            self.currentFetchedResultsController = self.nsfrc2;     
            [self.tableView reloadData];
        }
    }
    

    one UITableViewDataSource method as example:

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return [[self.currentFetchedResultsController sections] count];
    }
    

    and you have to make sure that only the current nsfrc triggers a tableview update in the NSFetchedResultsControllerDelegate methods. So you have to change all of them too.

    - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
        if (controller == self.currentFetchedResultsController) {
            [self.tableView beginUpdates];
        } 
    }
    

    EDIT: Nope, you are doing it wrong. the currentFetchedResultsController is just an ivar, without a lazy loading getter. It's "just" a pointer to the currently used controller.

    But the two other fetchedResultsControllers should have such a lazy loading getter.

    - (NSFetchedResultsController *)competitorFetchedResultsController {
        if (!myCompetitorFetchedResultsController) {
            // create competitorFetchedResultsController
        }
        return myCompetitorFetchedResultsController;
    }
    
    - (NSFetchedResultsController *)keyphraseFetchedResultsController {
        if (!myKeyphraseFetchedResultsController) {
            // create keyphraseFetchedResultsController
        }
        return myKeyphraseFetchedResultsController;
    }
    

    and then switch with:

    self.currentFetchedResultsController = self.keyphraseFetchedResultsController;
    

    or

    self.currentFetchedResultsController = self.competitorFetchedResultsController;
    
    0 讨论(0)
提交回复
热议问题