现在iOS5真的这么简单了吗?
我曾经在 AppDelegate 中使用以下代码执行后台获取:
dispatch_queue_t downloadQueue = dispatch_queue_create("DownloadQueue", NULL);
dispatch_async(downloadQueue, ^{
self.myDownloadClass = [[MyDownloadClass alloc]initInManagedObjectContext:self.managedObjectContext];
[self.myDownloadClass download];
});
dispatch_release(downloadQueue);
我的下载类执行 NSURLConnection 来获取一些 XML 数据,使用 NSXMLParser 解析数据,然后更新核心数据中的复杂架构。我总是切换到主线程来实际更新核心数据。代码混乱,大量调用dispatch_sync(dispatch_get_main_queue()....
我的新代码如下所示:
NSManagedObjectContext *child = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[child setParentContext:self.managedObjectContext];
[child performBlock:^{
self.myDownloadClass = [[MyDownloadClass alloc]initInManagedObjectContext:child];
[self.myDownloadClass download];
}];
对我的 AppDelegate 中的其他代码进行一些小更改,将父模型对象上下文类型设置为 NSMainQueueConcurrencyType:
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil)
{
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
__managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
看起来效果很好。整个更新过程仍然在单独的线程中运行,但我不必创建线程。看起来就像魔法一样。
请记住,如果您想将更改提交到物理核心数据文件,您也可以在父上下文上调用 save: 。
我真的没有在这里问问题。我发布此内容是为了对其他人有所帮助,因为我在搜索新的 iOS5 托管对象上下文方法时发现的所有内容都只提供了高级详细信息,没有代码示例并且所有其他在后台获取核心数据的搜索都是旧的,有时非常旧,并讨论在 iOS5 之前如何做到这一点。