iOS - 将数据从UIAlertView添加到sqlite



我想问用户是否想将他的分数从游戏添加到高分,在输入中我想问他的名字。在他完成后,我有这样的代码:

ListOfScores *listOfScores =[[ListOfScores alloc] init];
        if ([listOfScores GetScoresCount] < 10) {
            [self ShowMessageBoxForHighScore];
        }
        else if([listOfScores GetLastScore] < self.ActualScore)
        {
            [self ShowMessageBoxForHighScore];
        }
- (void)ShowMessageBoxForHighScore
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"save score" message:@"input username:" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    alert.tag = 12;
    [alert addButtonWithTitle:@"save"];
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 12) {
        if (buttonIndex == 1) {
            UITextField *textfield = [alertView textFieldAtIndex:0];
            ListOfScores *listOfScores =[[ListOfScores alloc] init];
            Score* score = [[Score alloc] initWithName:textfield.text Points:self.ActualScore];
            [listOfScores AddScore:score];
        }
    }
}

以下是我检查和创建数据库的方法:

-(BOOL)CreateTableForScores {
    BOOL ret;
    int rc;
    // SQL to create new table
    NSString *sql_str = @"CREATE TABLE Scores (pk INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , Points INTEGER DEFAULT 0, Name VARCHAR(100))";
    const char *sqlStatement = (char *)[sql_str UTF8String];
    NSLog(@"query %s",sqlStatement);
    sqlite3_stmt *stmt;
    rc = sqlite3_prepare_v2(db, sqlStatement, -1, &stmt, NULL);
    ret = (rc == SQLITE_OK);
    if (ret)
    { // statement built, execute
        rc = sqlite3_step(stmt);
        ret = (rc == SQLITE_DONE);
    }
    sqlite3_finalize(stmt); // free statement
    NSLog(@"creating table");
    return ret;
}
-(BOOL)TableForScoresExists {
    sqlite3_stmt *statementChk;
    sqlite3_prepare_v2(db, "SELECT name FROM sqlite_master WHERE type='table' AND name='Scores';", -1, &statementChk, nil);
    bool boo = FALSE;
    if (sqlite3_step(statementChk) == SQLITE_ROW) {
        boo = TRUE;
    }
    sqlite3_finalize(statementChk);
    return boo;
}

和我的 AddScore 方法:

- (void) AddScore:(Score *)newScore
{
    @try {
        BOOL tableExists = self.TableForScoresExists;
        if(!tableExists)
        {
            tableExists = self.CreateTableForScores;
        }
        if(tableExists)
        {
                NSString *filename = @"database.sqlite";
                NSFileManager *fileManager = [NSFileManager defaultManager];
                NSString *bundlePath       = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:filename];
                NSString *documentsFolder  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
                NSString *documentsPath    = [documentsFolder stringByAppendingPathComponent:filename];
                //NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"Milionar.sqlite"];
                const char *sql = "INSERT INTO Scores(Points,Name) VALUES(?,?)";

                if (![fileManager fileExistsAtPath:documentsPath])
                {
                    BOOL success;
                    NSError *error = nil;
                    success = [fileManager copyItemAtPath:bundlePath toPath:documentsPath error:&error];
                    NSAssert(success, @"Unable to copy database: %@", error);
                }
                if(sqlite3_open([documentsPath UTF8String], &db) == SQLITE_OK)
                {
                    sqlite3_stmt *sqlStatement;
                    if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) == SQLITE_OK)
                    {
                        sqlite3_bind_int(sqlStatement, 1, newScore.Points); //
                        sqlite3_bind_text(sqlStatement, 2, [newScore.Name UTF8String], -1, SQLITE_TRANSIENT); //
                        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]);
    }
}

问题是在AddScore方法中,当我尝试检查数据库是否存在时,我得到false。但是当我不使用UIAlertView并且我用一些文本替换AddScore的调用警报时,我一切正常,并且保存了Score对象。问题出在哪里?为什么它在委托方法中不起作用?谢谢

CreateTableForScore 和 TableForScoresExists 都需要一个有效的数据库指针。

因此,在调用这两个属性中的任何一个之前,您需要先打开 db。

在当前的代码片段中,这两个函数都可能使用未初始化的数据库指针调用。

此外,如果您使用"CREATE TABLE IF NOT EXIST"(https://www.sqlite.org/lang_createtable.html),则不一定需要调用方法TableForScoresExists。这样可以节省一些代码。

您必须返回一个BOOL但您有一个bool。在 Obj-C 中,它们是不一样的。也许解决这个问题会有所帮助。

你确定这是正确的按钮索引吗?稍后在代码中调用[alert addButtonWithTitle:@"save"];

而不是调用 ShowMessageBoxForHighScore ,如果你只是调用它来测试这是否有效:

ListOfScores *listOfScores =[[ListOfScores alloc] init];
Score* score = [[Score alloc] initWithName:@"TestName" Points:10];
[listOfScores AddScore:score];

这可能有助于为您隔离问题。我的猜测是它可能与UIAlertView无关。

最新更新