1

我有CoreData和表相关NSFetchedResultsController的。控制器有上下文,它在主队列中创建并且只读。当然,tableviewcontroller实现NSFetchedResultsControllerDelegate协议。

看一下它实现的方法:

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
    switch (type) {
        case NSFetchedResultsChangeInsert:
            NSLog(@"Inserted in %@", [NSString stringWithUTF8String:dispatch_queue_get_label(dispatch_get_current_queue())]);
            [_tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

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

        case NSFetchedResultsChangeUpdate:
            NSLog(@"Updated in %@", [NSString stringWithUTF8String:dispatch_queue_get_label(dispatch_get_current_queue())]);
            [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;

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

在后台,我在我的应用程序中下载数据并更新数据库。数据库的更新总是一样的。它以我的数据管理器的方法更新:

- (void)saveDataInBackgroundInForeignContext:(void (^)(NSManagedObjectContext *))saveBlock completion:(void (^)(void))completion {
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    dispatch_async([delegate.dispatcher queueForDataSavingInModel:self.modelName], ^{
        [self saveDataInForeignContext:saveBlock];

        dispatch_sync(dispatch_get_main_queue(), ^{
            completion();
        });
    });
}


- (void)saveDataInForeignContext:(void (^)(NSManagedObjectContext *))saveBlock {
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {

        NSManagedObjectContext *localContext = [[NSManagedObjectContext alloc] init];
        [localContext setPersistentStoreCoordinator:coordinator];

        [localContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
        [self.managedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
        [[NSNotificationCenter defaultCenter] addObserver:self.managedObjectContext
                                                 selector:@selector(mergeChangesFromContextDidSaveNotification:)
                                                     name:NSManagedObjectContextDidSaveNotification
                                                   object:localContext];

        saveBlock(localContext);

        if (localContext.hasChanges) {

            [self updateLastUpdateDateInConformedUpdatedObjects:localContext];

            NSError *error = nil;
            BOOL success = [localContext save:&error];
            if (!success) {
                NSLog(@"Saving in foreign context failed. %@", error.userInfo);
            }
        }

        [localContext release];
    }
}

saveBlock我修改上下文中取决于来自服务器的数据。所以,结果我有奇怪的行为:

注意NSLogcontroller:didChangeObject:atIndexPath第一个列表中的方法。让我们看看日志:

2012-11-16 02:59:33.376 [27824:5303] Inserted in ru.idecide.saving.calls // WTF WHY?!
2012-11-16 03:05:56.219 [27824:c07] Updated in com.apple.main-thread

ru.idecide.saving.calls - queue的保存数据。

这并不重要,一切正常,但是insertRowsAtIndexPaths在调用插入和(显然)立即更新后,方法会在 2-3 秒内对 UI 产生影响。为什么会发生,我能做些什么来避免它?

4

1 回答 1

1

问题在这里:

    [[NSNotificationCenter defaultCenter] addObserver:self.managedObjectContext
                                             selector:@selector(mergeChangesFromContextDidSaveNotification:)
                                                 name:NSManagedObjectContextDidSaveNotification
                                               object:localContext];

您将主线程上下文直接链接到后台队列上下文。当localContext在您的后台线程上运行时,发布通知时,通知将传递给self.managedObjectContext同一队列(后台队列)上的观察者()。

您需要先将通知传输到主线程,然后再将其传递给self.managedObjectContext. 给自己一个新方法来接收后台队列上的通知并将其转发到主线程:

- (void)backgroundContextDidSave:(NSNotification *)note {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.managedObjectContext mergeChangesFromContextDidSaveNotification:note];
    });
}

然后在注册通知时使用该方法选择器:

    [[NSNotificationCenter defaultCenter] addObserver:self.managedObjectContext
                                             selector:@selector(backgroundContextDidSave:)
                                                 name:NSManagedObjectContextDidSaveNotification
                                               object:localContext];
于 2012-11-16T06:19:18.800 回答