iPhone4 iOS5 NSFetchedResultsController как правильно установить делегата в подклассе? - PullRequest
0 голосов
/ 18 ноября 2011

У меня есть родительский класс, который обрабатывает все управление постоянными данными UITableview и управление строками UITableView. Я скопировал большую часть кода из нового проекта XCode4 с постоянными данными для UITableview. Теперь я пытаюсь удалить таблицу в дочернем классе, и ни один из методов делегата не вызывается при удалении строки, из-за чего мое представление таблицы остается в несогласованном состоянии.

Правильно ли я назначаю делегата? Кто является делегатом NSFetechedResultsController в этом случае? Нужно ли явно делать мой дочерний класс NSFetchedResultsControllerDelegate?

Вот как я могу получить NSFetchedResultsController, обратите внимание, как он назначает себя в качестве делегата.

- (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:entityName inManagedObjectContext:self.managedObjectContext];

    [fetchRequest setEntity:entity];

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

    // Edit the sort key as appropriate.
//    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"startMinute" ascending:YES];
    NSArray *sortDescriptors;
    if(sortDescriptor2!=nil)
    {
     sortDescriptors= [[NSArray alloc] initWithObjects:sortDescriptor,sortDescriptor2, nil];
    }else
    {
     sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    }
    [fetchRequest setSortDescriptors:sortDescriptors];

    if(filterPredicate != nil)
    {
        [fetchRequest setPredicate:filterPredicate];
    }

    // 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:@"Root"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;



    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;
}  

Когда приходит время удалять строки таблицы, ни один из методов делегата не вызывается, даже если строка таблицы действительно удалена. Чтобы устранить проблему, я добавил следующие 2 утверждения. Второе утверждение неверно.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    id delegate = self.fetchedResultsController.delegate;


    NSAssert(delegate!=nil,@"Tableview is not delegate of fetched results controller!");

//this assertion fails
    NSAssert([((UITableViewController*)self) isEqual:delegate],@"Tableview is not delegate of fetched results controller!");

    if (editingStyle == UITableViewCellEditingStyleDelete)
    {


        // Delete the managed object for the given index path
        NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];

        [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

        // Save the context.
        NSError *error = nil;
        if (![context save:&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();
        }
    }   
}

Спасибо!

Ответы [ 2 ]

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

Вы должны использовать эти методы для NSFetchedResultsController, чтобы иметь возможность реагировать на изменения в вашем табличном представлении:

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller;
{
    // The fetch controller is about to start sending change notifications, so prepare the table view for updates.
    [self.tableView beginUpdates];
}


- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
    switch(type) {
        case NSFetchedResultsChangeInsert:
            // your code for insert
        break;
        case NSFetchedResultsChangeDelete:
           // your code for deletion
        break;
    }
}

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

    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

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

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

        case NSFetchedResultsChangeMove:
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            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];
}

Также заставьте ViewController с помощью NSFetchedResultsController прослушивать NSFetchedResultsControllerDelegate.

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

Код для настройки NSFetchedResultsController выглядит правильно.Для его делегата установлено значение self, то есть делегат - это объект, в котором вы его создаете. Это похоже на тот же объект, который является делегатом для tableView.Выглядит так, как будто вы правильно удаляете объект и сохраняете контекст.

То, что вы не показываете и, вероятно, причиной сбоя, является ваша обработка методов делегата NSFetchedResultsController.Как минимум, вам нужно добавить следующее:

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

Это заставит таблицу перезагружаться всякий раз, когда fetchedResultsController обновляет себя, когда обнаруживает изменения в свой управляемыйObjectContext.

Если это не такПосле этого вам нужно опубликовать еще один код, показывающий, как настроены ваши классы и как вы обрабатываете методы делегата fetchedResultsController.

EDIT: исправлена ​​неправильная подпись om controllerDidChangeContent:

...