2011-08-30 45 views
10

我试图从我的应用程序包复制文件到我的应用程序的文档目录。我收到错误“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]); 
} 

回答

32

问题是你正在初始化一个普通的旧文件路径的URL。

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

改为使用[NSURL fileURLWithPath:]

3

你所得到的错误是

NSFileReadUnsupportedSchemeError Read error because the specified URL scheme is unsupported

我相信这将意味着你的路径之一是不正确形成。也许把这些路径写到日志中,看看它们是否按照你的预期出来。

+0

什么是正确的方案,你从哪里得到这些信息? – Moshe

+0

不要使用+ URLWithString:除非你想建立整个“file:/// path/to/file”路径。但为什么你会在+ fileURLWithPath时为你做这件事。 – kperryua

+0

从[链接](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html)获得了信息正确的方案几乎意味着你的网址被格式化。 – smitec

1

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

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

+0

这两个值都是完整的。 – Moshe

+0

它们是file:// URLs? –

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变量的值。

相关问题