我的副本在这里出了什么问题?

时间:2011-08-30 01:12:00

标签: iphone objective-c core-data copy nsfilemanager

我正在尝试将应用程序包中的文件复制到应用程序的文档目录中。我收到一个错误,“Cocoa Error 262”。我究竟做错了什么?这是我的代码:

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreData.sqlite"];
NSURL *initialURL = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"CoreData" ofType:@"sqlite"]];

NSError *error = nil;

if (![[NSFileManager defaultManager] fileExistsAtPath:[initialURL absoluteString]]) {
    NSLog(@"Original does not exist. \nPath: %@", [initialURL absoluteString]);
}  

if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL absoluteString]]) {
    NSLog(@"Destination file does not exist. \nPath: %@", [storeURL absoluteString]);

    [[NSFileManager defaultManager] copyItemAtURL:initialURL toURL:storeURL error:&error];

    NSLog(@"Error: %@", [error description]);
}

4 个答案:

答案 0 :(得分:32)

问题是您正在使用普通的旧文件路径初始化URL。

NSURL *initialURL = 
    [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"CoreData" 
                                                         ofType:@"sqlite"]];

改为使用[NSURL fileURLWithPath:]

答案 1 :(得分:3)

您收到的错误是

NSFileReadUnsupportedSchemeError Read error because the specified URL scheme is unsupported

我认为这意味着你的一条路径没有正确形成。或许将这些路径写入日志,看看它们是否按照您的预期出现。

答案 2 :(得分:2)

我已经解决了这个问题,虽然说实话,但我不确定它是什么。我必须再次查看工作代码,但现在是:

    NSError *error = nil;


NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", @"CoreData", @"sqlite"]];

//if file does not exist in document directory, gets original from mainbundle and copies it to documents.

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    NSString *defaultFilePath = [[NSBundle mainBundle] pathForResource:@"CoreData" ofType:@"sqlite"];
    [[NSFileManager defaultManager] copyItemAtPath:defaultFilePath toPath:filePath error:&error];

    if (error != nil) {
        NSLog(@"Error: %@", error);
    }
}

修改:

我怀疑应用程序目录的路径不正确,因为生成的applicationDocumentsDirectory的主体看起来与上面显示的documentsDorectory变量的值所使用的方法不同。

答案 3 :(得分:1)

错误262在FoundationErrors.h中定义为NSFileReadUnsupportedSchemeError。

我建议您使用NSLog()写出您正在使用的两个URL的文字值,并确保它们是file:// URL并且它们看起来很完整。

相关问题