[英]How to store & retrieve NSArray object in sqlite database in objective c
我想在sqlite數據庫的單列中存儲和檢索NSArray對象。 有誰知道我怎么能做到這一點?
實現此目的的最簡單方法是將數組轉換為JSON字符串並將該字符串存儲在數據庫中,同時在獲取數據時將JSON字符串再次轉換為數組。
數組到JSON
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrayObject options:NSJSONWritingPrettyPrinted error:nil]
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
JSON到數組
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *arrayObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
有很多方法可以做到這一點。 一種簡單的方法是使用componentsJoinedByString方法。
NSArray* someArray = @[.....];
NSString* result = [someArray componentsJoinedByString:@"<some separator>"];
你也可以NSKeyedArchiver
NSArray* someArray = @[.....];
NSData* dataToSave = [NSKeyedArchiver archivedDataWithRootObject:someArray];
但是,您將以數組形式提供對象,以確認NSCoding協議。
您也可以使用json序列化:
NSArray* someArray = @[.....];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:someArray options:NSJSONWritingPrettyPrinted error:nil]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.