2010-07-20 25 views
2

,我發現了以下錯誤:sqlite3_prepare_v2問題

*終止應用程序由於未捕獲的異常 'NSInvalidArgumentException',原因是: '* + [NSString的stringWithUTF8String:]:NULL CString的' 關於

下面的代碼行:

NSString *aName = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 1)]; 

我不知道這是怎麼回事,我在我的SQL語句中引用的列包含數據。下面的完整代碼。

// Open the database from the users filessytem 
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) 
    { 
     // Setup the SQL Statement and compile it for faster access 
     const char *sqlStatement = "select ZROUTE_NAME from ZROUTE"; 
     sqlite3_stmt *compiledStatement; 
     if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) 
     { 
      // Loop through the results and add them to the Route Name array 
      while(sqlite3_step(compiledStatement) == SQLITE_ROW) 
      { 
       // Read the data from the result row 
       NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]; 

       // Add the animal object to the animals Array 
       //[list addObject:animal];    
       [list addObject:aName];    
       //[animal release]; 
      } 
     } 
     else 
     { 
      NSLog(@"Error: failed to select details from database with message '%s'.", sqlite3_errmsg(database)); 
     } 

     // Release the compiled statement from memory 
     sqlite3_finalize(compiledStatement);   
    } 
    sqlite3_close(database); 

回答

3

處理NULL指針條件語句

if((char*)sqlite3_column_text(compiledStatement, 1) != NULL) 
{ 
     NSString *aName = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 1)]; 
} 

這將解決您的問題。

謝謝,
吉姆。

+1

這有完全相同的問題。你不應該檢查'NSString',而是檢查原始的C字符串。 – Joost 2010-07-20 10:26:42

+0

是的,我的錯誤。現在更正。感謝JoostK。 – Jim 2010-07-20 10:33:47

+0

感謝Jim&JoostK,我改變了我的代碼,如上所述。請注意,我不得不將sqlite3_column_text(compiledStatement,1)更改爲sqlite3_column_text(compiledStatement,0),不太清楚爲什麼,但現在它的工作。 – Stephen 2010-07-20 10:39:14

4

Ahhh:p - 我相信 - 如果你實施以下聲明,你不會有麻煩。

這不會拋出異常,因爲你所提到的 - *終止應用程序由於未捕獲的異常 'NSInvalidArgumentException',原因是: '* + [NSString的stringWithUTF8String:]:NULL CSTRING'

但是請記住 - 當有空值 - 你的字符串將有(null)

NSString *bName=[NSString stringWithFormat: @"%s",(char *)sqlite3_column_text(compiledStmt, 0)]; 

就是這樣。 UpVote如果發現有幫助。 :)

+0

我喜歡這個,但它引發了我的數據庫中是否有NULL的問題,我是否需要一個'nil'' NSString *'或者不是。 – lol 2012-02-20 13:28:01

相關問題