fetchedResultsContext на самом деле не удаляет объект и вызывает проблему утверждения в commitEditingStyle - PullRequest
0 голосов
/ 20 мая 2011

У меня странная проблема, и мне нужна помощь.

Я работаю с основным проектом данных и еще не использовал fetchedResultsController, просто работаю с fetchRequets и массивами для заполнения zableviews. Поэтому теперь я решил изменить и использовать FRC ...

Пока все было довольно просто ... но с commitEditingStyle у меня возникли проблемы с тех пор - при удалении строк выдается исключение, подобное этому:

The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update.

В конце концов я обнаружил, что это потому, что объект, который я хочу удалить, остается в FRC ... Я поместил некоторые разделы NSLog в liko так:

    NSLog(@"Number before deleting: %i - deleting %@",[[fetchedResultsController fetchedObjects] count], [fetchedResultsController objectAtIndexPath:indexPath]);

    NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
    [context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]];

    NSLog(@"Number before saving: %i",[[fetchedResultsController fetchedObjects] count]);

    NSError *error;
    if (![context save:&error]) {

        [NSException raise:NSGenericException format:@"Following error occured when trying to delete %@: %@", [fetchedResultsController objectAtIndexPath:indexPath], [error description]];
    }

    NSLog(@"Number after saving: %i",[[fetchedResultsController fetchedObjects] count]);

    NSArray * cellsToDelete = [NSArray arrayWithObject:indexPath];
    [tableView deleteRowsAtIndexPaths:cellsToDelete withRowAnimation:UITableViewRowAnimationFade];

Результат был такой:

2011-05-20 14:49:35.398 Nivellator[6000:207] Number before deleting: 3
2011-05-20 14:49:35.399 Nivellator[6000:207] Number before saving: 3
2011-05-20 14:49:35.404 Nivellator[6000:207] Number after saving: 3

Конечно, меня тошнит, когда я говорю табличному представлению, что он получит 3 строки, но пропустит только две ... но что здесь не так?

Мой старый код выглядел так и работал без проблем ...

-(void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.entityTableView] == YES) {
        if (editingStyle != UITableViewCellEditingStyleDelete) {
            return;
        }

        if ([self.entityArray count] <= indexPath.row) {
            return;
        }

        Member *thisEntity = [self.entityArray objectAtIndex:indexPath.row];
        [delegate.managedObjectContext deleteObject:thisEntity];

        NSError *savingError = nil;

        if ([delegate.managedObjectContext save:&savingError] == YES) {

            // Remove the entity from the Array and delete the corresponding table cell with animation
            //
            [self.entityArray removeObject:thisEntity];

            NSArray * cellsToDelete = [NSArray arrayWithObject:indexPath];
            [tableView deleteRowsAtIndexPaths:cellsToDelete withRowAnimation:UITableViewRowAnimationFade];
        } else {
            /* Error handling missing */
        }
    }
}

ОК

В конце концов, дело дошло до RTFM ... поэтому я заставил его частично работать, изменив код, такой как:

-(void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.entityTableView] == YES) {
        if (editingStyle != UITableViewCellEditingStyleDelete) {
            return;
        }

        NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
        [context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]];

        NSError *error;
        if (![context save:&error]) {

            [NSException raise:NSGenericException format:@"Following error occured when trying to delete %@: %@", [fetchedResultsController objectAtIndexPath:indexPath], [error description]];
        }

        if ([fetchedResultsController performFetch:&error]) {

            [tableView beginUpdates];

            NSArray * cellsToDelete = [NSArray arrayWithObject:indexPath];
            [tableView deleteRowsAtIndexPaths:cellsToDelete withRowAnimation:UITableViewRowAnimationFade];

            [tableView endUpdates];
        } else {

            [NSException raise:NSGenericException format:@"Following error occured when trying to delete %@: %@", [fetchedResultsController objectAtIndexPath:indexPath], [error description]];
        }
    }
}

Но когда я использую разделы в моем FRC, я все еще получаю ту же ошибку ... Я не могу найти ничего больше, чем это сделать с FRC ...

Есть идеи?

1 Ответ

0 голосов
/ 20 мая 2011
  1. Удалить кеш FRC после удаления
  2. Убедитесь, что вы правильно реализовали методы делегирования FRC.
  3. Перед запуском методов делегирования FRC убедитесь, что вы заморозили таблицу с помощью beginUpdates.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...