2011-08-29 24 views
0

我從CoreData中獲取大約2500顆星以用於構建星圖,並且想要在後臺線程中計算座標等的大部分數學運算,原因很明顯。我的問題是,因爲我必須將CoreData對象作爲NSManagedObjectID s傳遞迴主線程,您將如何處理計算,例如後臺線程中的一組笛卡爾座標,並且(最好)在NSManagedObject子類中設置這些座標?CoreData - 後臺線程中的計算屬性

對於它的價值,這裏是我使用的是從CoreData獲取並傳遞給主線程的代碼片段:

// Context and Model 
NSManagedObjectContext *context = [self.dataProvider newManagedObjectContext]; 
NSManagedObjectModel *model = [self.dataProvider sharedManagedObjectModel]; 

// Fetch the stars 
NSArray *stars = [SkyObject getSkyObjectsBetweenMinCoords:minCoords 
               maxCoords:maxCoords 
                minMag:self.minimumMagnitude 
                maxMag:self.maximumMagnitude 
                model:model 
                context:context]; 

NSMutableArray *starIDs = [[NSMutableArray alloc] init]; 

// Add the star's objectID to the set 
for (SkyObject *star in stars) { 
    [starIDs addObject:star.objectID]; 
} 

// Pass objects across thread boundaries 
[self performSelectorOnMainThread:@selector(updateLocalContextWithObjectIDs:) withObject:starIDs waitUntilDone:YES]; 

// Release retained memory 
[starIDs release]; 
[context release]; 

回答

0

你通常不會「傳遞CoreData對象回主線程作爲NSManagedObjectIDs」,而是你將執行所有操作設置與上下文在後臺線程上運行被管理對象,那麼當你完成時,你會合並前景上下文和後臺上下文。

傳遞managedObjectIDs當然是可行的,但它是一種緩慢的方式去解決它,特別是如果您有數千個對象要處理。它也不像合併那樣更新整個對象圖。

+0

'你會合並前景上下文和背景上下文' - 你能指出我的一個例子嗎? –

+0

請參閱核心數據編程指南:使用通知在其他線程中跟蹤更改http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdConcurrency.html#//apple_ref/doc/uid/TP40003385-SW5 – TechZen

+0

這篇文章說的與你的回答所說的相反。 '要通過線程邊界從另一個上下文「傳遞」一個託管對象,您可以:在接收託管對象上下文中傳遞其對象ID(objectID)並使用objectWithID:或existingObjectWithID:error :. – iwasrobbed