无法将数据库文件复制到另一个文件夹

时间:2012-12-04 07:42:56

标签: ios xcode sqlite copy

我使用以下代码将数据库文件复制到其他文件夹只是为了制作临时写入文件。

BOOL success;
NSArray*dirPath;
NSString*docDir;
NSString*databasePath;
NSString*databaseName=@"EXPENSES";

//path for database
dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docDir=[dirPath objectAtIndex:0];
databasePath=[docDir stringByAppendingPathComponent:databaseName];

NSLog(@" docDir %@",docDir);
//check if present
NSFileManager*fm=[NSFileManager defaultManager];
success=[fm fileExistsAtPath:databasePath];

if(success)
{
    NSLog(@"DATA BASE Already present");
}
else
{

    //Copy from bundle to DocumentsDirectory on first run. Where DB won't be available in DocumentsDirectory.
    NSString*bundlePath=[[NSBundle mainBundle] pathForResource:@"EXPENSES" ofType:@""];
    NSError*error;
    success=[fm copyItemAtPath:bundlePath toPath:databasePath error:&error];

    if(success)
    {
        NSLog(@"DATA BASE Created successfully");
    }

} // End of else when DB not present in documents directory.

但该文件未复制,而应用程序崩溃时显示错误“reason:' * - [NSFileManager copyItemAtPath:toPath:error:]:源路径为nil'”请帮我调试代码谢谢

3 个答案:

答案 0 :(得分:1)

你在这里犯了两个错误。

  1. 您没有提到目标文件扩展名

    而不是NSString*databaseName=@"EXPENSES";

    使用NSString*databaseName=@"EXPENSES.sqlite";

  2. 此代码是实际问题:

    NSString*bundlePath=[[NSBundle mainBundle] pathForResource:@"EXPENSES" ofType:@""];
    
  3. 在这里,您告诉NSFileManager找到名称为"EXPENSES"的文件,其扩展名为"",可能没有符合这些条件的文件。因此源路径为nil。这就是应用程序崩溃的原因。

    通常,数据库文件的扩展名为sqlite。替换您的代码,如:

    NSString*bundlePath=[[NSBundle mainBundle] pathForResource:@"EXPENSES" ofType:@"sqlite"];
    

答案 1 :(得分:0)

尝试在forType中添加bundle数据库扩展名:
NSString*bundlePath=[[NSBundle mainBundle] pathForResource:@"EXPENSES" ofType:@"<extension>"];错误表明无法找到指定的文件。

答案 2 :(得分:0)

我已经摆脱了那个问题。我不知道它背后的逻辑是什么,我只是从SVN导出了新的数据库并添加到我的项目包中,它的工作非常好