-2

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

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.

但是文件没有复制,而是应用程序崩溃并出现错误“原因:' * -[NSFileManager copyItemAtPath:toPath:error:]: source path is nil'”请帮我调试代码谢谢

4

3 回答 3

1

你在这里犯了两个错误。

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

    代替NSString*databaseName=@"EXPENSES";

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

  2. 此代码是实际问题:

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

在这里,您要告诉NSFileManager找到具有名称的文件,"EXPENSES"并且它的扩展名""可能没有具有这些条件的文件。所以源路径将是nil. 这就是应用程序崩溃的原因。

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

NSString*bundlePath=[[NSBundle mainBundle] pathForResource:@"EXPENSES" ofType:@"sqlite"];
于 2012-12-04T08:20:58.970 回答
0

尝试为 ofType 添加捆绑数据库扩展名:
NSString*bundlePath=[[NSBundle mainBundle] pathForResource:@"EXPENSES" ofType:@"<extension>"];错误提示无法找到指定的文件。

于 2012-12-04T07:47:19.713 回答
0

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

于 2012-12-05T10:56:59.770 回答