replaceItemAtURL在iOS上没有错误但在OSX上运行正常

gle*_*enc 17 iphone core-data nsfilemanager ios-4.2

我正在为基于CoreData的应用程序实现手动触发的迁移过程,并且在迁移成功完成后,我正在尝试将迁移的数据库移回原始数据库的顶部replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:.

问题是在iOS上,我没有做任何事情会使这个方法返回YES,但是它也永远不会在错误指针中添加任何东西,以便让你看到出了什么问题.

我在其他地方读过的东西(例如http://www.cocoabuilder.com/archive/cocoa/287790-nsdoc-magic-file-watcher-ruins-core-data-migration.html)表明没有关闭所有的CoreData尝试替换之前的对象(例如NSMigrationManager,NSManagedObjectModel等)可能是原因,但事实并非如此.我甚至实现了一个两个文件创建和交换的东西,它根本不涉及CoreData DB,以验证CoreData的东西与它没有任何关系.

然后我在官方文档中注意到newitemURL应该在一个被认为适合临时文件的目录中.我认为这意味着URLForDirectory:inDomain:appropriateForURL:create:error:使用NSItemReplacementDirectory作为搜索路径返回的目录.

这也不起作用!我最终回到使用单独的操作实现替换逻辑,但这是非原子的,不安全的,所有这些都是坏事.

有没有人有一个在iOS上运行的代码片段,它可以从调用返回YES replaceItemAtURL或者实际将错误信息放入错误指针中?

任何帮助非常感谢.

编辑 - 测试代码包括在下面.这在application:didFinishLaunchingWithOptions:主线程上运行.

NSFileManager *fm = [[NSFileManager alloc] init];
NSError *err = nil;
NSURL *docDir = [NSURL fileURLWithPath:[self applicationDocumentsDirectory]];

NSURL *tmpDir = [fm URLForDirectory:NSItemReplacementDirectory
                           inDomain:NSUserDomainMask
                  appropriateForURL:docDir
                             create:NO
                              error:&err];

NSURL *u1 = [docDir URLByAppendingPathComponent:@"f1"];
NSURL *u2 = [tmpDir URLByAppendingPathComponent:@"f2"];
NSURL *repl = nil;

[fm createFileAtPath:[u1 path]
            contents:[[NSString stringWithString:@"Hello"]
                      dataUsingEncoding:NSUTF8StringEncoding]
          attributes:nil];

[fm createFileAtPath:[u2 path]
            contents:[[NSString stringWithString:@"World"]        
                      dataUsingEncoding:NSUTF8StringEncoding]
          attributes:nil];

BOOL test = [fm replaceItemAtURL:u1 withItemAtURL:u2 backupItemName:@"f1backup"
                         options:0 resultingItemURL:&repl error:&err];

// At this point GDB shows test to be NO but error is still nil
Run Code Online (Sandbox Code Playgroud)

Fra*_*ano 1

NSFileManager我在 iOS 上使用 URL 的所有方法都遇到了问题。但是,所有使用 Path 的方法都有效。所以我认为你应该使用removeItemAtPath:error:andcopyItemAtPath:toURL:error:来达到这个目的。

希望能帮助到你