这是我的代码我只得到数组中数据库的最后一个值,但我需要数组中的整个列值...
//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);
}
}
答案 0 :(得分:2)
问题是你在while
语句的循环中实例化一个新的可变数组。您希望在循环之前实例化它一次,而在循环内部仅addObject
实例化它。
NSString *sql = [NSString stringWithFormat:@"SELECT * FROM district_details"];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil)==SQLITE_OK) {
myarray = [[NSMutableArray alloc] initWithObjects:@"--select the value--",nil];
while (sqlite3_step(statement)==SQLITE_ROW) {
char *field2 = (char *)sqlite3_column_text(statement, 1);
field2Str = [[NSString alloc] initWithUTF8String:field2];
[myarray addObject:field2Str];
}
sqlite3_finalize(statement); // remember to finalize to prevent SQLite leak
}
答案 1 :(得分:2)
在使用它之前启动一次数组对象,如果你在循环中启动它,就像你这样做会丢失先前添加的对象并在堆内存中进行新的分配。
只需将此代码放在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);