0

コア データ UIManagedDocument のバックアップを作成し、iCloud に保存しようとしています。これをやろうとしてから2か月以上経ちましたが、その方法がわかりません。インターネットにはまったく情報がありません...少なくともローカルバックアップを作成しようとしていますが、これはコードです:

-(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.)", 
4

1 に答える 1

0

このコードをテストしたところ、正常に動作します。サンプルアプリはこちらhttp://ossh.com.au/design-and-technology/software-development/sample-library-style-ios-core-data-app-with-icloud-integration/

ターゲット ファイルが既に存在する場合、そのエラーが発生します。

/**  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 のデフォルトの Core Data モード) を使用している場合は、~wal および ~shm ファイルもコピーする必要があります。StoreContent ディレクトリ全体をコピーすることをお勧めします。

  • iCloud からファイルをコピーするには、メタデータ クエリを実行してファイルを検索し、ダウンロード ステータスを確認する必要があります。コピーする前に、ダウンロードをトリガーし、ファイルがダウンロードされていることを確認する必要があると思います。

于 2014-02-09T09:51:54.703 に答える