I want to store & retrieve NSArray object in single column of sqlite database. Does anyone knows how i can achieve that?
2
-
can you show some exampleAnbu.Karthik– Anbu.Karthik2017-02-22 11:56:09 +00:00Commented Feb 22, 2017 at 11:56
-
grade : [ { "gradeId" : 123, "gradeName" : "abc" }, { "gradeId" : 222, "gradeName" : "xyz" } ]Savita Pal– Savita Pal2017-02-22 12:01:58 +00:00Commented Feb 22, 2017 at 12:01
Add a comment
|
2 Answers
The easiest way to achieve this is convert the array to JSON string and store the string in database and while fetching the data convert the JSON string to array again.
Array to JSON
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrayObject options:NSJSONWritingPrettyPrinted error:nil]
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
JSON to Array
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *arrayObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
2 Comments
Jacob M. Barnard
github.com/jmbarnardgh/labqlite and github.com/jmbarnardgh/labqlite_model_generator may be able to assist you with the SQLite part
Mahesh Agrawal
i am also using the library github.com/ccgus/fmdb and github.com/nerdyc/FMDBHelpers to interact with the SQLite database file and i have a class which contains functions for CRUD operation for required models. Those are also helpful.
It's many way to do this. One of the simple is use componentsJoinedByString method.
NSArray* someArray = @[.....];
NSString* result = [someArray componentsJoinedByString:@"<some separator>"];
Also you can NSKeyedArchiver
NSArray* someArray = @[.....];
NSData* dataToSave = [NSKeyedArchiver archivedDataWithRootObject:someArray];
But you will provide object in array that confirm to the NSCoding protocol.
Also you can use json serialisation:
NSArray* someArray = @[.....];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:someArray options:NSJSONWritingPrettyPrinted error:nil]