core data update in background的更新版本。
在链接Grand Central Dispatch (GCD) with CoreData的帮助下创建了一个后台managedObjectContext,但是从核心数据中获取时出现错误
-(void) startTimerThread
{
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Add code here to do background processing
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
self.backgroundManagedObjectContext = context;
[self.backgroundManagedObjectContext setPersistentStoreCoordinator:self.managedObjectContext.persistentStoreCoordinator];
self.managedObjectContext = self.backgroundManagedObjectContext;
[self getDataFromFile];
dispatch_async( dispatch_get_main_queue(), ^{
// Add code here to update the UI/send notifications based on the
// results of the background processing
[[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadAppDelegateTable" object:nil];
[context release];
self.managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
});
});
}
在我的getDataFromFile
中,当我尝试从managedObjectContext
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setPredicate:[NSPredicate predicateWithFormat:@"date == max(date)"]];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"LogDetails" inManagedObjectContext:self.managedObjectContext];
同样的错误:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name LogDetails
任何人都可以建议我为什么会收到此错误。以前我试图创建一个给出相同错误的子managedObjectContext。
提前致谢。
答案 0 :(得分:1)
我不太清楚为什么要创建一个上下文并将其设置为self.backgroundManagedObjectContext,然后将其设置为self.managedObjectContext。我建议允许你的getDataFromFile方法接受一个上下文,这样你就可以从任何线程调用它。
你会有
- (void)getDataFromFileOnContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setPredicate:[NSPredicate predicateWithFormat:@"date == max(date)"]];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"LogDetails" inManagedObjectContext:context];
}
然后你可以这样做
-(void) startTimerThread
{
self.managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Add code here to do background processing
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[context setParentContext:self.managedObjectContext];
[self getDataFromFileOnContext:context];
dispatch_async( dispatch_get_main_queue(), ^{
// Add code here to update the UI/send notifications based on the
// results of the background processing
[[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadAppDelegateTable" object:nil];
});
});
如果您需要更多帮助,请告诉我。