1

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 example Commented Feb 22, 2017 at 11:56
  • grade : [ { "gradeId" : 123, "gradeName" : "abc" }, { "gradeId" : 222, "gradeName" : "xyz" } ] Commented Feb 22, 2017 at 12:01

2 Answers 2

7

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];
Sign up to request clarification or add additional context in comments.

2 Comments

github.com/jmbarnardgh/labqlite and github.com/jmbarnardgh/labqlite_model_generator may be able to assist you with the SQLite part
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.
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.