尝试制作sqlite的可写副本时出错

时间:2012-01-18 03:36:07

标签: objective-c ios cocoa-touch sqlite

我在Supporting Files文件夹中有我的数据库副本。我需要更新几个表,我正在尝试使用方法来制作db的可写副本。

- (void) createEditableDatabase
{
   BOOL success; 
   NSFileManager *fileManager = [NSFileManager defaultManager]; 
   NSError *error;
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
   NSString *documentsDir = [paths objectAtIndex:0];
   NSString *writableDB = [documentsDir stringByAppendingPathComponent:@"yc_ch.db"];
   success = [fileManager fileExistsAtPath:writableDB];
   NSString *defaultPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"yc_ch.db"]; 
   success = [fileManager copyItemAtPath:defaultPath toPath:writableDB error:&error];
   if (!success) 
   {
    NSAssert1(0, @"Failed to create writable database file:'%@'.", [error localizedDescription]);
   }
}

我已在根目录中创建(物理上)“Documents”文件夹。文档的层次结构如下所示:

enter image description here

当我运行我的应用程序时。我收到NSAssert1(0,@“无法创建可写数据库文件:'%@'。”,[error localizedDescription]);.

它出了什么问题?

1 个答案:

答案 0 :(得分:1)

即使文件中已存在该文件,您也会复制该文件,我认为如果文件已存在于目的地,NSFileManager copyFileAtPath:将返回NO,因此无法检查并提升您的NSAssert

success = [fileManager fileExistsAtPath:writableDB];
if (success)
{
    return;
}

因此,如果文档中已存在该文件,则不会复制该文件。如果这是导致错误的原因,你实际上可以发布断言,[error localizedDescription]至少会告诉你它现在有什么问题。

编辑:

- (void) createEditableDatabase
{
   BOOL success; 
   NSFileManager *fileManager = [NSFileManager defaultManager]; 
   NSError *error;
   NSString *writableDB = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"yc_ch.db"];
   NSLog(@"Document path = %@", writableDB);
   success = [fileManager fileExistsAtPath:writableDB];
   if (success)
   {
       return;
   }
   NSString *defaultPath = [[NSBundle mainBundle] pathForResource:@"yc_ch" ofType:@"db"];
   NSLog(@"defaultPath = %@", defaultPath);
   error = nil;
   success = [fileManager copyItemAtPath:defaultPath toPath:writableDB error:&error];
   if (!success) 
   {
       NSAssert1(0, @"Failed to create writable database file:%@", [error localizedDescription]);
   }
   if (error)
   {
        NSLog(@"error = %@", [error localizedDescription]);
   }
}