我在使用NSManagedObjectContext的
我从主UI线程触发异步数据下载(使用NSURLConnection的
在视图控制器中,在
一切似乎都运行良好,但有一件事情让我感到困扰。当我在 `downloadCompleted:` 方法中使用 `performBlock:` 而不是 `performBlockAndWait:` 时,通知好像会延迟。从后台线程执行 `save:` 到 `NSFetchedResultsController` 调用其委托之间需要相当长的时间(约为 5 秒)。当我使用 `performBlockAndWait:` 时,我没有观察到任何可见的延迟 - 委托被调用的速度与我在 `_dispatch_async_` 中调用 `saveToCoreData:` 的速度一样快。
有人以前遇到过这种情况吗?这是正常现象还是我在滥用某些东西?
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:
中,我将背景上下文与主要上下文合并,以便我的 NSFetchedResultsController 的代理方法被调用,从而可以更新视图:
- (void)contextChanged:(NSNotification*)notification
{
if ([notification object] == self.managedObjectContext) return;
[self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}
一切似乎都运行良好,但有一件事情让我感到困扰。当我在 `downloadCompleted:` 方法中使用 `performBlock:` 而不是 `performBlockAndWait:` 时,通知好像会延迟。从后台线程执行 `save:` 到 `NSFetchedResultsController` 调用其委托之间需要相当长的时间(约为 5 秒)。当我使用 `performBlockAndWait:` 时,我没有观察到任何可见的延迟 - 委托被调用的速度与我在 `_dispatch_async_` 中调用 `saveToCoreData:` 的速度一样快。
有人以前遇到过这种情况吗?这是正常现象还是我在滥用某些东西?
[self.managedObjectContext performBlockAndWait:...]
。 - Dan ShellyconnectionWithRequest:
会在“(...)启动相关NSURLConnection对象的异步加载操作的线程”上调用委托方法。这可以通过检查[NSThread isMainThread]
轻松观察到。 - Marcin Czenko