2010-02-12 58 views
1

我一直試圖從表中返回數據之前已經訪問過兩個表,但在這種情況下,它進入while語句,但沒有分配任何值,因爲一切都設置爲空值。從iPhone上的SQLite3獲取數據時出現問題

的代碼是:

NSMutableArray *all_species = [[NSMutableArray alloc] init]; 
sqlite3 *db_species; 
int dbrc_species; 
Linnaeus_LiteAppDelegate *appDelegate = (Linnaeus_LiteAppDelegate*) [UIApplication sharedApplication].delegate; 
const char* dbFilePathUTF8 = [appDelegate.dbFilePath UTF8String]; 
dbrc_species = sqlite3_open (dbFilePathUTF8, &db_species); 
if (dbrc_species) { 
    return all_species; 
} 
sqlite3_stmt *dbps_species; 
const char *queryStatement = "SELECT species_id, species_name, species_latin, species_genus FROM \ 
           linnaeus_species;"; 
if (sqlite3_prepare_v2 (db_species, queryStatement, -1, &dbps_species, NULL) == SQLITE_OK) { 
    sqlite3_bind_int(dbps_species, 1, [the_species_id intValue]); 
    while (sqlite3_step(dbps_species) == SQLITE_ROW) { 
     Species *species = [[Species alloc] init]; 
     NSLog(@"%@", sqlite3_column_int(dbps_species, 0)); 
     [species setSpecies_id:[[NSNumber alloc] initWithInt:sqlite3_column_int(dbps_species, 0)]]; 
     char *new_name = (char *) sqlite3_column_text(dbps_species, 1); 
     [species setSpecies_name:nil]; 
     if (new_name != NULL) { 
      [species setSpecies_name:[NSString stringWithUTF8String:(char *) sqlite3_column_text(dbps_species, 1)]]; 
     } 
     char *new_latin = (char *) sqlite3_column_text(dbps_species, 2); 
     [species setSpecies_latin:nil]; 
     if (new_latin != NULL) { 
      [species setSpecies_latin:[NSString stringWithUTF8String:(char *) sqlite3_column_text(dbps_species, 2)]]; 
     } 
     [species setSpecies_genus:[NSNumber numberWithInt:sqlite3_column_int(dbps_species, 3)]]; 

     [species setEdited:0]; 
     [all_species addObject:species]; 
     [species release]; 
    } 
    sqlite3_finalize(dbps_species); 
} 
else { 
    sqlite3_close(db_species); 
} 

我使用的NSLog也嘗試(@ 「數據:%@」,sqlite3_column_text(dbps_species,1));它會導致EXC_BAD_ACCESS錯誤,表明它可能與內存有關,但我看不出爲什麼。

回答

3
NSLog(@"Data: %@", sqlite3_column_text(dbps_species, 1)); 

會造成EXC_BAD_ACCESS由於sqlite3_column_text結果是一個C字符串(char*),而不是一個NSString*。要打印C字符串你需要的%s格式說明:

NSLog(@"Data: %s", sqlite3_column_text(dbps_species, 1)); 

另外,不要浪費時間打電話給sqlite3_column_text兩次,例如

char *new_name = (char *) sqlite3_column_text(dbps_species, 1); 
    [species setSpecies_name:nil]; 
    if (new_name != NULL) { 
     [species setSpecies_name:[NSString stringWithUTF8String:new_name]]; 
    } 
+0

感謝您的答覆:) 這可以解釋爲什麼我不能調試它呢!我認爲%@將允許任何內容類型:( – jedi58 2010-02-12 21:01:01

+0

現在我已經能夠調試,以顯示我已經能夠解決這個問題 - 謝謝!:D – jedi58 2010-02-12 21:10:25