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

时间:2011-02-04 15:19:59

标签: iphone core-data ios-4.2 nsfilemanager

我正在为基于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的东西与它没有任何关系。

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

这也不起作用!我最终回到使用单独的操作来实现替换逻辑,但这是非原子的,不安全的以及所有那些不好的东西。

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

任何帮助都非常感激。

编辑 - 测试代码包含在下面。这在主线程上的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

2 个答案:

答案 0 :(得分:1)

我在使用iOS上的网址时遇到了所有NSFileManager方法的问题。但是,使用Path工作的所有方法。因此,我认为您应该使用removeItemAtPath:error:copyItemAtPath:toURL:error:来实现此目的。

希望有所帮助

答案 1 :(得分:-1)

在mac文件系统中不区分大小写,但在IOS中。即使您无法在一个位置拥有两个具有相同名称但具有不同大小写的文件,但该路径区分大小写。因此,如果文件具有.JPEG,并且在您的代码中,您将通过.jpeg传递链接,它将失败。 可能不是你的情况,而是分享的内容

虽然奇怪的是它应该给你错误。