这是我第一次尝试在iOS中创建和访问SQLite数据库,我遵循了一个教程,但我无法做到这一点。这些是我遵循的步骤:
在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"];
但它是空的,并且在我的应用程序中也低估并重新部署了我的应用程序模拟器好几次......
提前致谢
答案 0 :(得分:2)
我终于通过简单地删除在运行模拟器时再次创建的 / Users / [user] / Library / Application Support / iPhone Simulator / 5.1 / Applications / 中生成的app文件夹来完成此工作