2013-03-07 136 views
0

我需要在後臺線程中基本更新我的核心數據,而不會阻止UI並保存它。保存後應重新加載表視圖以查看更改。因此,對於這樣做我想用核心數據在後臺更新

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]; 
    }); 
}); 

,並在getDataFromFile當我試圖獲取數據

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

我得到錯誤*終止應用程序由於未捕獲的異常「NSInternalInconsistencyException」,原因:' + entityForName:實體名稱'LogDetails''找不到NSManagedObjectModel'

任何人都可以解釋爲什麼我得到這個錯誤

此外,我還有一個疑問是否將它包含在背景managedObjectContext或子級managedObjectContext與父級作爲主線程managedObjectContext

+0

我建議你閱讀這個偉大的教程:http://www.cocoanetics.com/2012/07/multi-context-coredata/ – rckoenes 2013-03-07 11:20:40

+0

我讀了幾個鏈接http://stackoverflow.com/questions/2138252/ core-data-multi-thread-application,http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/CoreData/Articles/cdConcurrency.html,http://www.cimgf.com/2011/05/04/core-data-and-threads-without-the-headache /並且還包括鏈接http://www.cocoanetics.com/2012/07/multi-context-coredata/但我仍然不是能夠找到我錯在哪裏 – aparna 2013-03-07 11:27:16

+0

你在哪裏設置parentObject?像'self.backgroundManagedObjectContext = main.managedObjectContext'等,在使用'NSPrivateQueueConcurrencyType'時不需要設置PersistentStoreCoordinator',而應該使用'[self.backgroundManagedObjectContext performBlock:(block)]' – rckoenes 2013-03-07 11:34:21

回答

1

一個NSManagedContext應該只能在一個線程中使用。在線程之間傳遞NSManagedObject可能是不安全的。