如何在iPhone上将sqlite ReadOnly更改为ReadWrite?

时间:2009-11-09 11:42:14

标签: iphone sqlite

我将我的应用程序部署到我的iPhone并获得

Unknown error calling sqlite3_step (8: attempt to write a readonly database) eu 插入/更新语句。

在模拟器上,它的工作原理应该如此。

我的sqlite数据库放在资源文件夹(Xcode)中。

感谢您的帮助!

2 个答案:

答案 0 :(得分:6)

您的应用程序包在iPhone上无法写入。您必须将文件复制到其他位置,例如文档文件夹。它可以在模拟器中运行,因为Mac不会强制执行iPhone所有的沙盒限制。

答案 1 :(得分:1)

您可以将数据库从应用程序包目录复制到viewDidLoad中的Documents目录。在此之后,您可以在Documents目录中读/写数据库。当然,在进行复制之前,您需要检查Documents目录中的数据库是否存在,以便在下次启动应用程序时不会覆盖它。

假设您已在.m文件中定义了数据库名称'#define kFilename @“yourdatabase.db”。

在viewDidLoad中添加:


// Get the path to the main bundle resource directory.

NSString *pathsToReources = [[NSBundle mainBundle] resourcePath];

NSString *yourOriginalDatabasePath = [pathsToResources stringByAppendingPathComponent:kFilename];

// Create the path to the database in the Documents directory.

NSArray *pathsToDocuments = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [pathsToDocuments objectAtIndex:0];

NSString *yourNewDatabasePath = [documentsDirectory stringByAppendingPathComponent:kFilename];

if (![[NSFileManager defaultManager] isReadableFileAtPath:yourNewDatabasePath]) {

if ([[NSFileManager defaultManager] copyItemAtPath:yourOriginalDatabasePath toPath:yourNewDatabasePath error:NULL] != YES)

NSAssert2(0, @"Fail to copy database from %@ to %@", yourOriginalDatabasePath, yourNewDatabasePath);

}

祝你好运!

的AOB