objective-c - 如何检索sqlite列值并将其存储到 objective-c 中的数组中?

标签 objective-c sqlite

这是我的代码,我只获取数组中数据库的最后一个值,但我需要数组中的整个列值...

//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/

相关文章:

objective-c - 单独类中的 UIAlertViewDelegate 会使应用程序崩溃

sqlite - 在不依赖 glib 的情况下使用来自 vala 的 sqlite

java - 使用 UNION 组合相同的 SQL 表并搜索特定单词返回重复行

sqlite - 检查 SQlite 中文本的编码

sql - 为什么我会遇到外键不匹配的情况?

Perl-SQLite3 : Basic Question

ios - iOS 5和iOS 6中UITabbar的区别

objective-c - NSDateFormatter 解析带和不带毫秒的 ISO8601

objective-c - 查看 Pages Mac OS X 应用程序使用的层次结构

objective-c - 在 WebKit 上的 Mac OS 应用程序中启用 WebGL