2017-03-21 9 views
1

は、ここで私は、アレイ内のデータベースの唯一の最後の値を取得しています私のコードですが、私はsqliteの列の値を取得し、目的のCの配列に格納する方法は?

//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); 
    } 

} 

答えて

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); 
+0

ありがとう – pavithra

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  
} 
+0

正しいについて説明します。 – vaibhav

関連する問題