对于两个核心数据实体A和B,其中A与B具有一对多关系,我试图在后台上下文中执行获取,其父级是主要上下文[与UI相关联]。由于我需要以预取方式获得结果,即核心数据也必须填充关系,如下所示[使用MagicalRecord]:
NSManagedObjectContext* bgContext = [NSManagedObjectContext context];
[bgContext performBlock:^{
NSpredicate * searchPredicate = <some search criteria in entity A>
if(!searchPredicate){
dispatch_async(dispatch_get_main_queue(), ^{
//completionBlock is a callback block to be executed on main thread. completionBlock(nil);
return;
});
}
//Using below request to get relationship data in pre-fetch format.
NSFetchRequest* aRequest = [A requestAllSortedBy:@"<aColumn>" ascending:YES withPredicate:searchPredicate inContext:bgContext];
[aRequest setReturnsObjectsAsFaults:YES];
[aRequest setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObject:@"photos"]];//photos is a relationship between A and B
[aRequest setIncludesPropertyValues:YES];
[aRequest setIncludesSubentities:YES];
NSArray *as = [A executeFetchRequest:aRequest inContext:bgContext];
if (as == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(nil);
return;
});
}
NSArray *objectIDs =[as valueForKey:@"objectID"];
NSManagedObjectContext *mainContext = [NSManagedObjectContext defaultContext];
[mainContext performBlock:^{
//temporary bad solution
NSMutableArray *entities = [[NSMutableArray alloc] init];
for (A *a in as) {
[entities addObject:[a inContext:mainContext]];
}
completionBlock([NSArray arrayWithArray:entities]);
}];
}];
虽然结果正如预期的那样,但我仍然想知道上面是否接近评论&#34; //临时不良解决方案&#34;是否有效。 即使我将objectID传递给主上下文,那么在这种情况下如何预先获取关系?
答案 0 :(得分:0)
最好的选择是获取所有托管对象ID并将其传递给主线程。然后,根据主线程的要求,从对象ID批量加载托管对象并缓存托管对象实例(刷新它们以将它们变成故障但如果内存不足则保留托管对象)。