我遇到了有趣的行爲,當使用NSManagedObjectContext的performBlock:
與通知中心。NSManagedObjectContext:performBlockAndWait與performBlock與通知中心
從主UI線程我觸發異步數據下載(使用NSURLConnection的connectionWithRequest:
)。當數據到達下面的委託方法被調用:
- (void)downloadCompleted:(NSData *)data
{
NSArray *new_data = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.backgroundObjectContext = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSPrivateQueueConcurrencyType];
self.backgroundObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator;
[self.backgroundObjectContext performBlockAndWait:^{
[self saveToCoreData:new_data];
}];
}
的savetoCoreData:
方法簡單地保存新的數據到後臺背景:
- (void)saveToCoreData:(NSArray*)questionsArray
{
for (NSDictionary *questionDictionaryObject in questionsArray) {
Question *newQuestion = [NSEntityDescription
insertNewObjectForEntityForName:@"Question"
inManagedObjectContext:self.backgroundObjectContext];
newQuestion.content = [questionDictionaryObject objectForKey:@"content"];
}
NSError *savingError = nil;
[self.backgroundObjectContext save:&savingError];
}
在視圖控制器,在viewDidLoad
我添加觀察員通知中心:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextChanged:)
name:NSManagedObjectContextDidSaveNotification
object:nil];
然後在contexChanged:
我合併背景上下文與主要上下文,所以臨時T分別叫我NSFetchedResultsController的委託方法在我的視圖可以更新:
- (void)contextChanged:(NSNotification*)notification
{
if ([notification object] == self.managedObjectContext) return;
[self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}
這一切似乎運作良好,但有一件事困擾我。當我在downloadCompleted:
方法中使用performBlock:
而不是performBlockAndWait:
時,通知似乎被延遲。從後臺線程執行直到NSFetchedResultsController調用其委託時,需要大量時間(大約5秒)。當我使用performBlockAndWait:
時,我沒有觀察到任何可見的延遲 - 代表被呼叫的速度如同我在_dispatch_async_
內呼叫saveToCoreData:
一樣快。
有沒有人看到過,並知道這是正常的還是我濫用的東西?
請注意,通知是在後臺線程中引發的,並且您將後臺線程中的主要上下文合併到非常不適宜的主環境中。使用'[self.managedObjectContext performBlockAndWait:...]' –
這確實很有道理。謝謝丹!我沒有意識到''connectionWithRequest:'調用了委託方法「(...)啓動相關NSURLConnection對象的異步加載操作的線程。通過檢查'[NSThread isMainThread]'可以很容易地觀察到這一點。 –