这是我的代码,我只获取数组中数据库的最后一个值,但我需要数组中的整个列值...
//select the values from the db
NSString *sql = [NSString stringWithFormat:@"SELECT * FROM district_details"];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil)==SQLITE_OK)
{
while (sqlite3_step(statement)==SQLITE_ROW)
{
char *field2 = (char *)sqlite3_column_text(statement, 1);
field2Str = [[NSString alloc]initWithUTF8String:field2];
str = [NSString stringWithFormat:@"%@", field2Str]; NSLog(@"the value from thr field1 from the district name is %@...",field2Str);
myarray =[[NSMutableArray alloc]initWithObjects:@"--select the value--",nil];
[myarray addObject:field2Str];
NSLog(@"the value of the myarray is......%@",myarray);
}
}
最佳答案
在使用数组对象之前,先初始化一次数组对象,如果像在do那样在while循环内部初始化它,它将丢失先前添加的对象,并在堆内存中进行新分配。
只需将这段代码放入viewDidLoad
方法中并从while循环中删除:
- (void)viewDidLoad {
[super viewDidLoad];
// mutable array allocation do once here
myarray =[[NSMutableArray alloc]initWithObjects:@"--select the value--",nil];
}
现在使用下面的代码从数据库中获取整个列:
//select the values from the db
NSString *sql = [NSString stringWithFormat:@"SELECT * FROM district_details"];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil)==SQLITE_OK)
{
while (sqlite3_step(statement)==SQLITE_ROW)
{
char *field2 = (char *)sqlite3_column_text(statement, 1);
field2Str = [[NSString alloc]initWithUTF8String:field2];
// --------- myarray allocation removed from here -----------
[myarray addObject:field2Str];
NSLog(@"the value of the myarray is......%@",myarray);
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
关于objective-c - 如何检索sqlite列值并将其存储到 objective-c 中的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42920050/