我需要将从 Sqlite 数据库返回的结果存储到 NSMutableArray 中而不指定数据类型。
sqlite3_value *sqlvalue = (sqlite3_column_value(sqlStat, 0));
对不起我的英语不好,最好的问候。
尝试这个:
const char *value = (const char *)sqlite3_column_value(sqlStat, 0)
如果你真的想这样做,你可以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);