core data update in background

偶尔善良 提交于 2020-01-11 07:47:34

问题


I need to basically update my core data in a background thread without blocking UI and save it. After saving should reload table View to view the changes. So for doing this I thought of using

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Add code here to do background processing
   NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    self.backgroundManagedObjectContext = context;
    if(self.managedObjectContext == nil)
        self.managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    self.backgroundManagedObjectContext.parentContext = self.managedObjectContext;

    //update data
    [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];
    });
});

and in getDataFromFile when I try to fetch data

if(![NSThread isMainThread])
{
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"LogDetails" inManagedObjectContext:self.backgroundManagedObjectContext];
    [request setEntity:entity];
    logs = [self.backgroundManagedObjectContext executeFetchRequest:request error:nil];
}

I get error * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'LogDetails''

can anyone explain why I am getting this error

Also I have an another doubt whether to include it as background managedObjectContext or child managedObjectContext with parent as main thread managedObjectContext


回答1:


One NSManagedContext should only be used in one thread. passing NSManagedObject between threads are potentially unsafe.



来源:https://stackoverflow.com/questions/15269768/core-data-update-in-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!