【发布时间】:2015-05-03 10:55:25
【问题描述】:
我从几个异步调用的 Web 服务中获取了一些数据。当我收到他们的回复时,我需要使用收到的信息在 Core Data 中创建和保存相应的实体。由于服务回调是异步的,当我收到另一个服务时,我可能已经保存了其中一个服务的响应,所以我写了几个这样的方法:
- (void)createEntity
{
@autoreleasepool {
dispatch_queue_t queue = dispatch_queue_create(kSaveQueue, NULL);
dispatch_async(queue, ^{
// Context for background operations
NSManagedObjectContext *tmpContext = [[NSManagedObjectContext alloc] init];
NSPersistentStoreCoordinator *mainThreadContextPSC = [self.context persistentStoreCoordinator];
[tmpContext setPersistentStoreCoordinator:mainThreadContextPSC];
@try {
// Parse service response and create entity
// Save context
[tmpContext save:nil];
dispatch_async(dispatch_get_main_queue(), ^{
// Notify end of operation
});
}
@catch (NSException *ex) {
NSLog(@"exception: %@", [ex description]);
}
});
}
}
实际上,我有两种这样的方法,一种用于假设EntityA,另一种用于EntityB,当我收到相应的服务响应(serviceA,serviceB)时会调用每个方法。在我的测试中,我看到 tmpContext 始终保存在 iOS 8 中,但在 iOS 7 中,它只是第一个被保存的,而第二个实体没有保存在 Core Data 中。
为什么这在 iOS 8 中有效,但在 iOS 7 中无效?
提前致谢
【问题讨论】:
标签: ios core-data concurrency grand-central-dispatch nsmanagedobjectcontext