【发布时间】:2012-09-30 15:15:44
【问题描述】:
这是我第一次尝试在 iOS 中创建和访问 SQLite 数据库,我按照教程进行操作,但我无法完成这项工作。这些是我遵循的步骤:
- 通过 Firefox 插件(“testDatabase”)和一个 具有多列的表(“testTable”)
- 将“testDatabase.sqlite”文件保存在目录中
- 将此类文件拖放到我的“支持文件”组中 Xcode 项目
- 在构建阶段添加了“libsqlite3.dylib”> 链接二进制文件 图书馆
- 在构建设置 > 链接 > 其他链接器标志中添加了“-lsqlite3”> 调试和发布
-
在一个ViewController中,调用了这个方法:
-(NSString *)copyDatabaseToDocuments { NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; NSString *filePath = [documentsPath stringByAppendingPathComponent:@"testDatabase.sqlite"]; if ( ![fileManager fileExistsAtPath:filePath] ) { NSString *bundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"testDatabase.sqlite"]; [fileManager copyItemAtPath:bundlePath toPath:filePath error:nil]; } return filePath; } -
然后,尝试写入数据库:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; NSString *filePath = [documentsPath stringByAppendingPathComponent:@"testDatabase.sqlite"]; sqlite3 *database; if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) { const char *sqlStatement = "insert into testTable (id) VALUES (?)"; sqlite3_stmt *compiledStatement; if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { sqlite3_bind_int(compiledStatement, 1, newObject.ID); } if(sqlite3_step(compiledStatement) == SQLITE_DONE) { sqlite3_finalize(compiledStatement); } } sqlite3_close(database);
我已经阅读了几篇关于类似错误的帖子,但我尝试过的所有方法都没有对我有用...我也尝试了 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"testDatabase" ofType:@"sqlite"]; 但它为空,并且还低估并在模拟器中重新部署了我的应用程序次...
提前致谢
【问题讨论】:
-
在构建应用程序时,您是否验证过 testDatabase.sqlite 文件实际上是应用程序包的一部分(与 Info.plist 和您的其他资源在同一目录中?
-
是的,它位于那个目录下,它也在目标的 Build Phases > Copy Bundle Resources 中列出
标签: ios ios5 sqlite ios-simulator