我正在使用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。
提前致谢!
答案 0 :(得分:0)
您正在使用“半永久”FRC(它是您的控制器的实例变量),但将其设置为使用“临时”MOC,当没有人再使用它时它将消失。
我不遵循你真正想做的事情,但我认为如果你存储“临时”MOC,它会起作用。但是,您必须首先询问为什么要这样做。
在parentContext和performBlock
之间插入代码 context.parentContext = peopleDoc.managedObjectContext;
// Keep the MOC with the FRC...
self.myBackgroundFetchingMoc = context;
[context performBlock:^{