2014-02-09 40 views
0

我想问一下,如果用户想将他的分数从游戏添加到高分和输入中,我想问他的名字。他完成后,我有这样的代码: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方法中,当我试图检查数据库是否存在时,我得到了错误。但是当我不使用UIAlertView时,我用一些文本替换了将AddScore调用的警报替换掉,我得到了一切正常,并保存了Score对象。哪里有问题?为什么它不能在委托方法中工作?谢谢

+0

您是否尝试过在该委托方法中打印textfield.text?只是为了看看它实际上是否返回一些字符串? – jovanjovanovic

+0

是的,我有正确的数据在那里。 –

+0

看起来你正在重新初始化'didDismissWithButtonIndex'中的'listOfScores'? – Thompson

回答

1

CreateTableForScores和TableForScoresExists都需要一个工作的数据库指针。

因此,您需要在调用这两个属性之前先打开数据库。

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

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

1

您必须返回一个BOOL但您有一个bool。在Obj-C中它们不一样。也许修复可以帮助。

+0

我修好了,但它仍然没有工作。 –

0

您确定它的按钮索引正确吗?

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

这可能会帮助隔离问题你:你在你的代码

+0

是的,当我有断点时,我得到了添加新分数的方法。 'tableExists'不是整个时间(甚至在'self.CreateTableForScores'调用之后)。 –

0

与其说ShowMessageBoxForHighScore,如果你只需要调用这个测试,如果这个工程的后来打电话[alert addButtonWithTitle:@"save"];。我的猜测是,这可能与UIAlertView无关。

+0

正如我写的问题。当我移除UIAlertView并用一些值调用AddScore时,一切都很好。 –

相关问题