Как я могу обновить свой fetchedResultsController при выборе строки tableView? - PullRequest
2 голосов
/ 04 ноября 2011

Хорошо, я поправляюсь в этих базовых данных, но у меня есть способы пойти.Вот как я заполняю свой fetchedResultsController, когда мое представление загружается:

- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil)
{
    return __fetchedResultsController;
}

/*
 Set up the fetched results controller.
 */
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Visit" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];

// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

[fetchRequest setSortDescriptors:sortDescriptors];

// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Queue"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;

NSPredicate *predicate =[NSPredicate predicateWithFormat:@"(isActive == YES)"];
[fetchedResultsController.fetchRequest setPredicate:predicate];

NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error])
{
    /*
     Replace this implementation with code to handle the error appropriately.

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
     */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return __fetchedResultsController;
}

Это прекрасно работает.У меня есть fetchedResultsController, подключенный к моему tableView, и у меня есть 5 управляемых объектов, которые отображаются.Проблема, с которой я сталкиваюсь, заключается в том, что мне нужно внести изменения в один из управляемых объектов.

Как вы можете видеть в предикате, я указываю, что мне нужны только управляемые объекты, имеющие isActive == YES.Мне нужно изменить статус isActive управляемого объекта на NO, а затем удалить его из fetchedResultsController и, в конечном итоге, tableView.

Вот как я пытаюсь это сделать:Похоже, что это будет работать, но это не так.Когда tableView перезагружается, 5 объектов возвращаются в соответствии с требованиями предиката, когда его должно быть только 4!

Что я здесь не так делаю?Что мне нужно сделать, чтобы обновить fetchedResultsController?Спасибо!

Ответы [ 2 ]

1 голос
/ 04 ноября 2011

Существуют методы делегата для fetchedResultsController, которые вы, возможно, захотите использовать, которые должны сделать все это для вас автоматически.Как только вы сохраните контекст, он обновит таблицу для вас, поэтому вам не придется вызывать [tableView reloadData]

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

- (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:UITableViewRowAnimationFade];
            break;

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

- (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:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

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

        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView endUpdates];
}

РЕДАКТИРОВАТЬ: если вы сделаете это, вам нужно будет реализовать следующий метод:

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    // configure cell;
}
0 голосов
/ 04 ноября 2011

Я почти уверен, что добавление следующего кода в ваш метод seatedButton непосредственно перед строкой с [tableView reloadData] решит проблему, но не уверен в соответствии с документом, что это должно быть необходимо.

if (![self.fetchedResultsController performFetch:&error])
{
    /*
     Replace this implementation with code to handle the error appropriately.

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
     */
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}
...