SQLite步骤失败:尝试写入只读数据库,使用包装器。

4

在使用此代码复制数据库时,我一直收到错误信息“SQLite Step Failed: attempt to write a readonly database”。

-(void)createEditableCopyOfDatabaseIfNeeded 
{
    // Testing for existence
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                           NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath =
            [documentsDirectory stringByAppendingPathComponent:@"Money.sqlite"];

    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success)
        return;

    // The writable database does not exist, so copy the default to
    // the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
            stringByAppendingPathComponent:@"Money.sqlite"];
    success = [fileManager copyItemAtPath:defaultDBPath
                           toPath:writableDBPath
                           error:&error];
    if(!success)
    {
        NSAssert1(0,@"Failed to create writable database file with Message : '%@'.",
                 [error localizedDescription]);
    }
}

我正在AppDelegate中使用上述代码,以及这段代码:

NSString *writableDBPath =
        [[NSBundle mainBundle] pathForResource:@"Money"
                               ofType:@"sqlite"];

在ViewController.m文件中

我正在使用http://th30z.netsons.org/2008/11/objective-c-sqlite-wrapper/,我做错了什么?

这一直发生...之前它一直运行良好,但问题又出现了。

1个回答

7
问题是您无法向包中写入任何内容。为了能够更改数据库,您需要将其复制到应用程序的文档或缓存文件夹,并使用该副本进行操作。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Money.sqlite"];当我使用上述代码时,它显示表未找到! - Omkar Jadhav
复制数据库后,我又成功地解决了问题。 - Omkar Jadhav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接