Core data UImanagedDocument';s persistentStore iCloud备份

Core data UImanagedDocument';s persistentStore iCloud备份,core-data,icloud,uimanageddocument,nspersistentstore,Core Data,Icloud,Uimanageddocument,Nspersistentstore,我正在尝试为核心数据UIManagedDocument创建备份,并将其存储在iCloud中。我已经两个月没有试过这么做了,我不知道该怎么做。互联网上根本没有任何信息。。。 我正在尝试创建本地备份,但它也不起作用 代码如下: -(void)testCopyStoreToDocuments { AppDelegate* appDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate; [appDelegate.

我正在尝试为核心数据UIManagedDocument创建备份,并将其存储在iCloud中。我已经两个月没有试过这么做了,我不知道该怎么做。互联网上根本没有任何信息。。。 我正在尝试创建本地备份,但它也不起作用 代码如下:

-(void)testCopyStoreToDocuments
{
    AppDelegate* appDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.userDataDocument closeWithCompletionHandler:^(BOOL closed)
     {
         if(closed)
         {
             @autoreleasepool {
                 NSFileCoordinator *fc = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
                 NSString *sourceFile = [[[[LoadingManager localDocumentURL]URLByAppendingPathComponent:@"StoreContent"]path] stringByAppendingPathComponent:@"persistentStore"];
                 NSURL *sourceURL = [NSURL fileURLWithPath:sourceFile];

                 [fc coordinateReadingItemAtURL:sourceURL options:NSFileCoordinatorReadingWithoutChanges error:nil byAccessor:^(NSURL *sourceURLtoUse) {
                     NSError *error = nil;
                     NSFileManager *fm = [[NSFileManager alloc] init];
                     NSString *destinationFile = [[[LoadingManager localDocumentsDirectoryURL]path] stringByAppendingPathComponent:@"persistentStore"];


                     //simply copy the file over
                     BOOL copySuccess = [fm copyItemAtPath:[sourceURLtoUse path]
                                                    toPath:destinationFile
                                                     error:&error];
                     if (copySuccess) {
                         NSLog(@" copied file successfully");
                     } else {
                         NSLog(@"Error copying item at path: %@\nTo path: %@\nError: %@", sourceFile, destinationFile, error);
                     }
                 }];
                 fc = nil;
             }

         }
     }];
}
-(void)testReplaceStore
{
    AppDelegate* appDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.userDataDocument closeWithCompletionHandler:^(BOOL closed)
     {
         if(closed)
         {
             NSFileCoordinator *fc = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
             [fc coordinateWritingItemAtURL:[[[LoadingManager localDocumentURL]URLByAppendingPathComponent:@"StoreContent"]URLByAppendingPathComponent:@"persistentStore"] options:NSFileCoordinatorWritingForDeleting error:nil byAccessor:^(NSURL *sourceURLtoUse){
                 NSLog(@"%@",sourceURLtoUse);
                 NSError * error = nil;
                 NSLog(@"replacment: %hhd",[[NSFileManager defaultManager]replaceItemAtURL:sourceURLtoUse withItemAtURL:[[LoadingManager localDocumentsDirectoryURL]URLByAppendingPathComponent:@"persistentStore"] backupItemName:@"backUp" options:NSFileManagerItemReplacementUsingNewMetadataOnly resultingItemURL:nil error:&error]);
                 NSLog(@"%@",error);
             }];
             NSLog(@"stores: %@",appDelegate.userDataDocument.managedObjectContext.persistentStoreCoordinator.persistentStores);
             [appDelegate.userDataDocument saveToURL:appDelegate.userDataDocument.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL saved)
              {
                  if(saved)
                  {
                      [appDelegate.userDataDocument openWithCompletionHandler:^(BOOL opened)
                       {
                           if(opened)
                           {
                               NSLog(@"opened");
                           }

                       }];
                  }
                  else
                  {
                      NSLog(@"failed to save");
                      NSLog(@"stores: %@",appDelegate.userDataDocument.managedObjectContext.persistentStoreCoordinator.persistentStores);
                  }
              }];
         }
     }];
}
调用“替换”时会记录一个错误:

 replacment: 0
 Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x15d91540 {NSFileNewItemLocationKey=file:///var/mobile/Applications/85974C93-75FD-406A-B1BF-EDE7DFC25FE2/Documents/persistentStore, NSFileOriginalItemLocationKey=file:///var/mobile/Applications/85974C93-75FD-406A-B1BF-EDE7DFC25FE2/Documents/Data%20Document/StoreContent/persistentStore, NSUnderlyingError=0x15db0080 "The operation couldn’t be completed. (Cocoa error 260.)", 

我刚刚测试了这段代码,效果很好。下面是一个示例应用程序

如果目标文件已存在,则会出现该错误

/**  Copies file to iCloud container removing the target file if it already exists

 @param docURL  URL of UIManagedDocument whose store file is to be copied (its Core Data Store must not be shared in iCloud!
 */
- (void)copyFileToICloud:(NSURL*)docURL {
    @autoreleasepool {
        NSFileCoordinator *fc = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
        NSURL *sourceURL = [[docURL URLByAppendingPathComponent:@"StoreContent"] URLByAppendingPathComponent:@"persistentStore"];

        // Local directory - test
        //NSString *destinationFile = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"persistentStore_backup"];

        NSURL *destinationURL = [[[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil] URLByAppendingPathComponent:@"Documents"] URLByAppendingPathComponent:@"persistentStore_backup"];


        FLOG(@" source file is %@", sourceURL);
        FLOG(@" target file is %@", destinationURL);

        NSError *cError;

        [fc coordinateWritingItemAtURL:destinationURL options:NSFileCoordinatorWritingForReplacing error:&cError byAccessor:^(NSURL *newURL) {
            NSError *error = nil;
            NSFileManager *fm = [[NSFileManager alloc] init];

            // Delete it if it already exists
            if ([fm fileExistsAtPath:[newURL path]]) {
                FLOG(@" target file exists");
                if (![fm removeItemAtURL:newURL error:&error]) {
                    FLOG(@" error unable to remove target file");
                    NSLog(@"Error removing item Error: %@, %@", error, error.userInfo);
                    return;
                } else {
                    FLOG(@" target file removed");
                }
            }

            //simply copy the file over
            BOOL copySuccess = [fm copyItemAtPath:[sourceURL path]
                                           toPath:[newURL path]
                                            error:&error];
            if (copySuccess) {
                NSLog(@" copied file successfully");
            } else {
                NSLog(@"Error copying items Error: %@, %@", error, error.userInfo);
            }
        }];

        if (cError) {
            FLOG(@" error is %@", cError);
        }

        fc = nil;
    }
}
编辑:需要记住的其他一些事情:

  • 如果您使用的是WAL模式(或iOS7、OS X 10.9的默认核心数据模式),那么您还必须复制~WAL和~shm文件—最好复制整个StoreContent目录

  • 要从iCloud复制文件,您必须执行元数据查询以查找文件,然后检查下载状态,我认为您必须触发下载并检查文件是否已下载,然后才能进行复制


如果您描述了使用上述代码遇到的问题,将会有所帮助。@TomHarrington我更新了问题文件是否已经存在?检查目标文件是否已经存在,并在复制之前将其删除!!顺便说一句,cocoa error 260是NSFileReadNoSuchFileError=260,//读取错误(没有这样的文件),因此源文件名可能不正确。在模拟器中运行应用程序,并确认这些文件路径实际上是正确的。此外,如果核心数据存储在iCloud中共享,则需要从存储获取存储文件URL。核心数据将其放在自己的某个目录中,因此UIManagedDocument报告的路径不正确。使用模拟器检查实际路径是否正确。