从AppDelegate获取persistentStoreCoordinator时出错

时间:2015-02-03 15:18:56

标签: ios core-data grand-central-dispatch nsmanagedobjectcontext

我正在开发一个iOS 7+应用程序,其数据被请求RESTful服务。当应用程序启动时,我执行了几个异步服务请求,有时当我收到其中一个的响应时我收到Core Data错误,我想用我收到的信息创建和保存对象。

由于我以异步方式接收服务的响应,因此对于每个响应,我使用临时NSPersistentStoreCoordinator并在分离的线程中执行插入,如下所示:

@autoreleasepool {
    dispatch_queue_t queue = dispatch_queue_create(kDataUpdateQueue, NULL);
    dispatch_async(queue, ^{
        NSManagedObjectContext *tmpContext = [[NSManagedObjectContext alloc] init];
        NSPersistentStoreCoordinator *mainThreadContextPSC = [self.context persistentStoreCoordinator];
        [tmpContext setPersistentStoreCoordinator:mainThreadContextPSC];

        @try {
            // Objects insertion in tmpContext

            [tmpContext save:nil];

            dispatch_async(dispatch_get_main_queue(), ^{
                // Notify end
            });
        }
        @catch (NSException *ex) {
           NSLog(@"exception: %@", [ex description]);
        }
    });
}

我通常直接在iOS 8设备上运行应用程序,有时我在Xcode的调试区域出现错误,如下所示:

Unresolved error Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data" UserInfo=0x188c7190 {NSLocalizedDescription=Failed to initialize the application's saved data, NSUnderlyingError=0x18969600 "The operation couldn’t be completed. (Cocoa error 134080.)", NSLocalizedFailureReason=There was an error creating or loading the application's saved data.}, {
NSLocalizedDescription = "Failed to initialize the application's saved data";
NSLocalizedFailureReason = "There was an error creating or loading the application's saved data.";
NSUnderlyingError = "Error Domain=NSCocoaErrorDomain Code=134080 \"The operation couldn\U2019t be completed. (Cocoa error 134080.)\" UserInfo=0x189695e0 {NSUnderlyingException=Can't add the same store twice}";}

AppDelegate persistentStoreCoordinator获取者,当到达NSPersistentStoreCoordinator *mainThreadContextPSC = [self.context persistentStoreCoordinator];行时,self.context为:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
return appDelegate.managedObjectContext;

正如我所说,并不总是得到这个错误,我甚至第一次运行应用程序,然后没有以前的核心数据文件...我发现这很奇怪,为什么会发生这种情况?

提前致谢

编辑:如果我添加此内容:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
   @synchronized(self) {
      // Rest of the code provided by default
   }
}

- (NSManagedObjectContext *)managedObjectContext
{
   @synchronized(self) {
      // Rest of the code provided by default
   }
}

看起来我再也没有收到错误日志了。这可能是解决方案,还是我只是转移/延迟问题?

再次感谢

0 个答案:

没有答案