NSFetchedResultsController在insertNewObjectForEntityForName上调用无限次数的委托方法:inManagedObjectContext:

Jos*_*sen 2 database core-data save

[编辑]我正在改变这一点,以更简洁地解释我的问题是什么,在更精确地确定问题之后.

我正在为我的应用程序处理核心数据,但我很难过.它每次都挂在这个方法中.没有崩溃,没有日志,没有任何东西.它只是挂起.

- (void)insertNewObject:(id)sender
{
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
    NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];

    Section *newSection = (Section *)newObject;
    newSection.title = @"inserted";


    NSError *error = nil;

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

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

NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
Run Code Online (Sandbox Code Playgroud)

我发现如果我把NSLogs放在这两个委托方法中:

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
Run Code Online (Sandbox Code Playgroud)

他们只是被称为无限次.

Jos*_*sen 8

好的,我明白了.我正在创造一个无限循环.

调用此委托方法:

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
Run Code Online (Sandbox Code Playgroud)

然后这最终被调用因为我调用[self.tableView beginUpdates]; 在委托方法中.

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

    {
        Section *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
        object.title = [NSString stringWithFormat:@"Chapter %i", indexPath.row];
        cell.textLabel.text = object.title;

    }
Run Code Online (Sandbox Code Playgroud)

然后这个委托方法:

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
Run Code Online (Sandbox Code Playgroud)

问题是我实际上在更新内容时更改了NSManagedObject的属性

object.title = [NSString stringWithFormat:@"Chapter %i", indexPath.row];
Run Code Online (Sandbox Code Playgroud)

这导致controllerWillChangeContent:再次被调用,创建一个循环的循环.

  • 通过在更新内容时不更改“NSManagedObject 的属性” (2认同)