2013-10-08 70 views

回答

1

如果你真的想這樣做,你可能會爲你的陣列NSData(例如,使用NSKeyedArchiver),然後使用sqlite_bind_blob寫信給你的數據庫,並使用sqlite_column_blob檢索。顯然,如果您在該陣列中有任何自定義對象,則必須實施適當的NSCoder方法。個人而言,我寧願讓我的數據模型鏡像我的數組結構,而不是將我的數組存儲爲blob。但這兩種技術都有效。


到數組保存到數據庫中,你可以做到以下幾點:

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"one", @"two", @"three", nil]; 

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array]; 
NSAssert(data, @"archivedDataWithRootObject failed"); 

sqlite3_stmt *statement; 

rc = sqlite3_prepare_v2(database, "insert into test (test_array) values (?)", -1, &statement, NULL); 
NSAssert(rc == SQLITE_OK, @"prepare failure: %s", sqlite3_errmsg(database)); 

rc = sqlite3_bind_blob(statement, 1, [data bytes], [data length], SQLITE_TRANSIENT); 
NSAssert(rc == SQLITE_OK, @"bind failure: %s", sqlite3_errmsg(database)); 

rc = sqlite3_step(statement); 
NSAssert(rc == SQLITE_DONE, @"step failure: %s", sqlite3_errmsg(database)); 

sqlite3_finalize(statement); 

,並檢索數組:

rc = sqlite3_prepare_v2(database, "select test_id, test_array from test", -1, &statement, NULL); 
NSAssert(rc == SQLITE_OK, @"prepare failure: %s", sqlite3_errmsg(database)); 

rc = sqlite3_step(statement); 
NSAssert(rc == SQLITE_ROW, @"step failure: %s", sqlite3_errmsg(database)); 

const void * bytes = sqlite3_column_blob(statement, 1); 
NSAssert(bytes, @"unable to retrieve bytes from database: %s", sqlite3_errmsg(database)); 
int length = sqlite3_column_bytes(statement, 1); 

NSData *resultData = [NSData dataWithBytes:bytes length:length]; 

NSMutableArray *newArray = [NSKeyedUnarchiver unarchiveObjectWithData:resultData]; 
NSAssert(newArray, @"Unable to unarchiveObjectWithData"); 

sqlite3_finalize(statement); 
+0

例如在java中,我可以從SQlite獲取任何數據並存儲在Object類型變量中,然後轉換爲我想要的數據類型。 –

+0

非常感謝羅布。 –

2

試試這個:

const char *value = (const char *)sqlite3_column_value(sqlStat, 0) 
+0

感謝您的答覆。是的,我嘗試過,但我得到罕見的字符。是否有可能在NSMuttableArray中投入ID存儲? –

+0

您可以將該char []轉換爲NSString並存儲它 –

+0

那麼請將它轉換爲id以便存儲在nsmuttablearray中? –

相關問題