gpt4 book ai didi

iphone - 在 iPhone 上从 SQLite3 获取数据时出现问题

转载 作者:行者123 更新时间:2023-12-03 18:41:05 27 4
gpt4 key购买 nike

在已经访问过两个表之后,我一直在尝试从表中返回数据,但在这种情况下,它进入了 while 语句,但由于所有内容都设置为 null,因此不分配任何值。

代码是:

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(@"Data: %@", sqlite3_column_text(dbps_species, 1));它会导致 EXC_BAD_ACCESS 错误,这表明它可能与内存有关,但我不明白为什么。

最佳答案

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]];
}

关于iphone - 在 iPhone 上从 SQLite3 获取数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2253637/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com