How do I best implement parsing JSON into CoreData?

243 views Asked by At

I can't wrap my mind around the following: How do I best implement parsing JSON into CoreData?

I already know how to parse JSON and de-serialize it, but how do I get the result into CoreData?

At the moment I have a LoginViewController that sends a NSURLRequest with username & pw to a webserver and receives an echo, which is a JSON-file.

And I already have set up the AppDelegate.h & AppDelegate.m with the CoreDataStack

My Question: How do I get the NSDictionary (JSON-result) from the LoginViewController into the database? Do I have to call a method in the app delegate? Or should I place CoreDataStack in LoginViewController?

2

There are 2 answers

0
Piyush On BEST ANSWER

Alex, try using Restkit, its really efficient in persisting JSON response directly to Core Data
Use the URL request to fetch the JSON, it maps the entire response to Core Data. You can even modify the payload before persisting.
Communication is internally handled with the help of widely used AFNetworking
A little initial configuration that is required, but the results are worth the effort!

0
Tom Harrington On

It sounds like what you're really after is how to get a reference to the Core Data stack from the code that parses the JSON. If that's the case, the quick and dirty way is just to ask the app delegate for it. That's something simple like

NSManagedObjectContext *context = [[[UIApplication sharedApplication] delegate] managedObjectContext];

You'll probably need to #import "AppDelegate.h" and typecast the result of the delegate call to keep the compiler handy.

It's almost certainly a bad idea to set up the Core Data stack in your login view controller-- unless that's the only place you ever use it (which I'm betting is not the case). It's often a good idea to set it up somewhere other than the app delegate though. For example, a new class that's responsible for managing the stack and which implements any general Core Data-related methods you find you need.

If getting the data from your NSDictionary into a managed object is actually the problem, I wrote about this last year at Cocoa is my Girlfriend, and that advice still stands.