0

我正在使用 UIDocument 访问核心数据并尝试在后台线程中设置 NSFetchedResultsController 以不阻塞主 UI。如果我使用 uidocument 的 managedobjectcontext 而不是孩子,它会起作用。我在堆栈溢出时从此处的答案之一中获取了其中的一些代码,但无法使其与 fetchedresultscontroller 一起使用。

[ZH peopleDocumentusingBlock:^(UIManagedDocument *peopleDoc){
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        context.parentContext = peopleDoc.managedObjectContext;
        [context performBlock:^{
             NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
           request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"key" ascending:YES]];
            [NSFetchedResultsController deleteCacheWithName:nil];
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"imageurl.length>0"];
            request.predicate = predicate;

            NSError *error = nil;
            if(!self.totalNumberOfPeople) //set total number of people for this fetch used for show more records
            {
                self.totalNumberOfPeople = [context countForFetchRequest:request error:&error]; 
                NSLog(@"total number of people -> %d",self.totalNumberOfPeople);

            }

                self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:@"peopleCache"];
dispatch_async(dispatch_get_main_queue(), ^{
                    [self.delegate refreshPeoplelTableview];
                    NSLog(@"fetched objects -> %d",[self.fetchedResultsController.fetchedObjects count]);
                    NSLog(@"total number of people -> %d",self.totalNumberOfPeople);


                });
    }];
}];

实际上context countforfetchrequest会但不是 fetcheresultscontroller。

提前致谢!

4

1 回答 1

0

您正在使用“半永久性”FRC(它是控制器的实例变量),但将其设置为使用“临时”MOC,当没有人再使用它时,它就会消失。

我不遵循您真正想做的事情,但是我认为如果您存储“临时” MOC,它将起作用。但是,您必须首先问为什么要这样做。

在 parentContext 和 performBlock 之间插入代码

    context.parentContext = peopleDoc.managedObjectContext;
    // Keep the MOC with the FRC...
    self.myBackgroundFetchingMoc = context;
    [context performBlock:^{
于 2012-07-02T23:22:52.723 回答