NSFetchedResultsController:在后台线程中获取

时间:2013-02-10 22:14:11

标签: ios multithreading core-data uiviewcontroller nsfetchedresultscontroller

我有一个或多或少的基本UITableViewController NSFetchedResultsControllerUITableViewController被推送到navigationController's堆栈。但推送动画并不流畅,因为NSFetchedResultsController的获取是在主线程上执行的,因此会阻止UI。

我的问题是:如何在后台线程中执行NSFetchedResultsController的提取以保持动画流畅?

NSFetchedResultsController和委托方法如下所示:

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

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"GPGrade" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

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

    //Set predicate
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parent == %@", self.subject];
    [fetchRequest setPredicate:predicate];


    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    NSArray *sortDescriptors = @[sortDescriptor];

    [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:@"SubjectMaster"];
    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.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _fetchedResultsController;
}

- (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:@[newIndexPath] withRowAnimation:UITableViewRowAnimationTop];
            break;

        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
            break;

        case NSFetchedResultsChangeUpdate:
            //[self configureCell:(GPSubjectOverviewListCell *)[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;

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

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

3 个答案:

答案 0 :(得分:18)

<强> TL; DR;没有充分的理由在主队列中使用上下文。

  

可以使用NSFetchedResultsController在后台获取数据

绝对。 NSFetchedResultsController可以与私有队列上下文一起使用。事实上,这样做非常快乐和高效。 There is a bug阻止NSFetchedResultsController在使用私有队列时使用它的缓存,但缓存并不像在iOS 3.0中那样赢得你。设置cacheName为零,你会没事的。

1.使用NSPrivateQueueConcurrencyType创建上下文。最好不要用于IO。

2.使用该上下文创建获取的结果控制器,缓存名称为nil。

3.performBlock:块内执行初始抓取:

 [[[self fetchedResultsController] managedObjectContext] performBlock:^{
    NSError *fetchError = nil;
    if (![self fetchedResultsController] performFetch:&error]){
        /// handle the error. Don't just log it.
    } else {
        // Update the view from the main queue.
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [tableView reloadData];
         }];
    }
 }];

4.现在所有的委托回调都会从上下文的队列中发生。如果您使用它们来更新视图,请通过调度到主队列来执行此操作,如上所示。

5. ...

6. 获利!

您可以阅读有关此here的更多信息。

答案 1 :(得分:1)

Core Data的一般规则是每个线程一个托管对象上下文,每个MOC一个线程。考虑到这一点,您需要在主线程上执行Fetched Results Controller的获取,因为这是将与FRC的托管对象进行交互的线程。 (见Core Data Programming Guide - Concurrency with Core Data

如果您遇到动画的性能问题,您应该考虑一些方法来确保在推送视图之前或之后执行提取。通常,您将在视图控制器的viewDidLoad:中执行提取,导航控制器在提取完成之前不会推送视图。

答案 2 :(得分:0)

您可以查看有关多线程行为的核心数据的nice帖子。

希望它有所帮助.. !!