Objective c 在UITableView中使用UISegmentedControl在NSFetchedResultsController之间切换

Objective c 在UITableView中使用UISegmentedControl在NSFetchedResultsController之间切换,objective-c,ios7,uitableview,uisegmentedcontrol,nsfetchedresultscontroller,Objective C,Ios7,Uitableview,Uisegmentedcontrol,Nsfetchedresultscontroller,我在一个项目中工作,我使用核心数据存储一些信息,我有一个UITableViewController,带有一个UISegmentedControl和两个NSFetchedResultsController,因为在切换分段控件时,我需要获取不同的数据 当我第一次打开表视图时,我可以看到与分段控制器的第一个索引相对应的数据,但是当我切换到第二个索引时,数据不会显示,当我返回到分段控制器的第一个索引时,数据也不会显示 这是密码 #import "TurnHistoryVC.h" #import "App

我在一个项目中工作,我使用核心数据存储一些信息,我有一个UITableViewController,带有一个UISegmentedControl和两个NSFetchedResultsController,因为在切换分段控件时,我需要获取不同的数据

当我第一次打开表视图时,我可以看到与分段控制器的第一个索引相对应的数据,但是当我切换到第二个索引时,数据不会显示,当我返回到分段控制器的第一个索引时,数据也不会显示

这是密码

#import "TurnHistoryVC.h"
#import "AppDelegate.h"
#import "Turn.h"
#import "TurnInfoVC.h"
#import "Favorite.h"

@interface TurnHistoryVC ()

@property (nonatomic, retain) NSFetchedResultsController *currentFRC;
@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, strong) NSFetchedResultsController *favoritesResultsController;

@end


@implementation TurnHistoryVC

@synthesize fetchedResultsController = _fetchedResultsController;
@synthesize favoritesResultsController = _favoritesResultsController;

- (void)viewWillAppear:(BOOL)animated{
    NSInteger *turn_id = [[NSUserDefaults standardUserDefaults] integerForKey: @"turn_noti_id"];
    if (turn_id != 0) {
        [self performSegueWithIdentifier:@"myTurn" sender:self];
    } else {
        id delegate = [[UIApplication sharedApplication] delegate];
        self.managedObjectContext = [delegate managedObjectContext];
        NSError *error;
        self.currentFRC = self.fetchedResultsController;
        if (![[self currentFRC] performFetch:&error]) {

            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

        }


    }
    [self.tableView reloadData];
    [super viewWillAppear:animated];

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Atrás" style:UIBarButtonItemStylePlain target:nil action:nil];

    [self.tableView reloadData];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.currentFRC sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell.
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {

    Turn *turn = [self.currentFRC objectAtIndexPath:indexPath];
    cell.textLabel.text = [NSString stringWithFormat:@"Turno no. %@", turn.turn_number];
    cell.detailTextLabel.text = turn.companie_info;
    cell.tag = [turn.turn_id intValue];

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    // Display the authors' names as section headings.
//    return @"";
    return [[[self.currentFRC sections] objectAtIndex:section] name];
}

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

    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    NSLog(@"cell id: %i", selectedCell.tag);

}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        self.editButtonItem.title = @"Listo";
        //        [tableView ]
        // Delete the managed object.
        NSManagedObjectContext *context = [self.currentFRC managedObjectContext];
        [context deleteObject:[self.currentFRC objectAtIndexPath:indexPath]];

        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
//            abort();
        }
    }
}

//Metodo para cambiar el texto del boton para borrar favoritos
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"Elimiar";
}

-(void)toggleEdit{
    [self.tableView setEditing:!self.tableView.editing animated:YES];
    if (self.tableView.editing){
        [self.navigationItem.leftBarButtonItem setTitle:@"Listo"];
    }else{
        [self.navigationItem.leftBarButtonItem setTitle:@"Editar"];
    }
}


#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([sender isKindOfClass:[UITableViewCell class]]){
        if ([segue.destinationViewController isKindOfClass:[TurnInfoVC class]]){
            TurnInfoVC *turnInfoVC = segue.destinationViewController;
            NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
            UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:indexPath];
            turnInfoVC.turn_id = selectedCell.tag;

        }
    }

}

#pragma mark - Cambio de turnos pendientes a finalizados

- (IBAction)btnTurnTypes:(UISegmentedControl *)sender {


    NSError *error;
    NSLog(@"cambie de tab 0");
    switch (sender.selectedSegmentIndex) {
        case 0:
        {
            self.currentFRC = self.fetchedResultsController;
            [self.tableView reloadData];

        }
        break;

        case 1:
        {
            self.currentFRC = self.favoritesResultsController;
            [self.tableView reloadData];
            NSLog(@"cambie de tab 1");
        }
        break;

        default:
            break;
    }
    [self.tableView reloadData];

}

#pragma mark - Fetched results controller

/*
 Returns the fetched results controller. Creates and configures the controller if necessary.
 */
- (NSFetchedResultsController *)fetchedResultsController {

    if (_fetchedResultsController != nil) {

    }
    NSLog(@"turnos pendientes");
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Turn"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"turn_confirmation==0 AND turn_status==1"];
    fetchRequest.predicate = predicate;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Turn" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];


    // Create the sort descriptors array.
    NSSortDescriptor *categoryDescriptor = [[NSSortDescriptor alloc] initWithKey:@"companie_info" ascending:YES];
    NSSortDescriptor *companyDescriptor = [[NSSortDescriptor alloc] initWithKey:@"turn_number" ascending:YES];
    NSArray *sortDescriptors = @[categoryDescriptor, companyDescriptor];
    [fetchRequest setSortDescriptors:sortDescriptors];

    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"companie_info" cacheName:@"Root"];
    _fetchedResultsController.delegate = self;
    self.currentFRC = _fetchedResultsController;
    return _fetchedResultsController;
}

- (NSFetchedResultsController *)favoritesResultsController {

    if (_favoritesResultsController != nil) {
    }
    NSLog(@"turnos finalizados");
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Turn"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"turn_confirmation==0 AND turn_status==0"];
    fetchRequest.predicate = predicate;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Turn" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    // Create the sort descriptors array.
    NSSortDescriptor *categoryDescriptor = [[NSSortDescriptor alloc] initWithKey:@"companie_info" ascending:YES];
    NSSortDescriptor *companyDescriptor = [[NSSortDescriptor alloc] initWithKey:@"turn_number" ascending:YES];
    NSArray *sortDescriptors = @[categoryDescriptor, companyDescriptor];
    [fetchRequest setSortDescriptors:sortDescriptors];

    // Create and initialize the fetch results controller.
    _favoritesResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"companie_info" cacheName:@"Root"];
    _favoritesResultsController.delegate = self;
    self.currentFRC = _favoritesResultsController;
    return _favoritesResultsController;
}

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    NSLog(@"actualizando fuera del if");
    // The fetch controller is about to start sending change notifications, so prepare the table view for updates.
    if (controller == self.currentFRC) {
        NSLog(@"actualizando dentro del if");
        [self.tableView beginUpdates];
    }
}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {

    UITableView *tableView = self.tableView;

    switch(type) {

        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;

        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;

        case NSFetchedResultsChangeUpdate:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;

        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
    }
}


- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
    switch(type) {

        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;

        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {

    // The fetch controller has sent all current change notifications, so tell the table view to process all updates.
    [self.tableView endUpdates];
}
@end
我已经试过了,但是没法用,谢谢