我正在尝试更新一行中的一个单元格,但我无法正常工作。更新方法:
- (void) UpdateQuestionShownParameter:(int)QuestionId :(BOOL)QuestionShown{
@try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"Milionar.sqlite"];
const char *sql = "UPDATE Questions set Show = ? WHERE id = ?";
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(@"Cannot locate database file '%@'.", dbPath);
}
if(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)
{
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) == SQLITE_OK)
{
NSInteger shownInteger = (QuestionShown ? 1 : 0);
sqlite3_bind_int(sqlStatement, 1, shownInteger);
sqlite3_bind_int(sqlStatement, 2, QuestionId);
if (sqlite3_step(sqlStatement) != SQLITE_DONE)
{
NSLog(@"Error while updating. '%s'", sqlite3_errmsg(db));
}
sqlite3_finalize(sqlStatement);
}
else
{
NSLog(@"Problem with prepare statement");
}
}
else
{
NSLog(@"An error has occured while opening database.");
}
sqlite3_close(db);
}
@catch (NSException *exception) {
NSLog(@"An exception occured: %@", [exception reason]);
}
}
在ViewDidLoad中尝试:
- (void)viewDidLoad
{
ListOfQuestions *listQuestions =[[ListOfQuestions alloc] init];
self.Questions = [listQuestions getQuestions];
Question *generatedQuestion = (Question *) [self.Questions objectAtIndex:0];
[listQuestions UpdateQuestionShownParameter:generatedQuestion.id :TRUE];
[self.Description setText:(generatedQuestion.Description)];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
每当我试图运行应用程序时,我会在显示的列中得到0。但我没有任何错误。所以,我做错了什么或每当我试图在模拟器中运行应用程序时,我从项目数据库中重新创建数据库? 感谢
答案 0 :(得分:3)
您正在打开捆绑包中的数据库,该数据库是只读的。如果数据库尚不存在于Documents文件夹中,您应该将数据库从bundle复制到Documents文件夹:
NSString *filename = @"Milionar.sqlite";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *bundlePath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:filename];
NSString *documentsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *documentsPath = [documentsFolder stringByAppendingPathComponent:filename];
if (![fileManager fileExistsAtPath:documentsPath]) {
NSError *error = nil;
BOOL success = [fileManager copyItemAtPath:bundlePath toPath:documentsPath error:&error];
NSAssert(success, @"Unable to copy database: %@", error);
}
if (sqlite3_open([documentsPath UTF8String], &db) != SQLITE_OK) {
NSLog(@"Open failed");
} else {
// ...
}
有关文档所属位置的详细信息,请参阅File System Programming Guide。
顺便说一下,如果您正在寻找模拟器的Documents文件夹,那么它位于~/Library/Application Support/iPhone Simulator
(在Xcode 6中,现在是~/Library/Developer/CoreSimulator/Devices
)。如果您没有看到“Library”文件夹,可以通过在终端命令行界面中键入以下命令来取消隐藏它:
chflags nohidden ~/Library