Core Data is a very powerful framework for persistent data management for iPhone developers. It allows you to define you data model by abstracting your model object. I am not going to talk about what Core Data is about and how to use it normally. A lot has been already written about it. Feel free to Google for it.
I will be sharing a practical problem I faced while using Core Data in combination with Tabbar, Navigation controller and tableview. When using the Interface Builder to create Tabbar and displaying the first View in Navigation controller, passing around the NSManagedObjectContext is a major issue. To be able to take full advantage of Core Data, one must use the existing managedObjectContext in order for all views to always have the latest updated data.
The Core Data documentation discourages us from retrieving the managedObjectContext from the application delegate as it makes the overall architecture design rigid. And as mentioned above, creating a new managedObjectContext for every view in your application is a bad idea.
A way to handle this situation is, to have the creator to set the managedObjectContext for the view before displaying it. I was using Interface Builder for managing for managing the Tabbar and Navigation controller and couldn’t really find a way to set managedObjectContext before initializing it.
So I simply created my tabs in the code directly and then it was as simple as adding one line to set managedObjectContext after calling init on the view controller.
Hope this solution will save someone from searching for hours for this kind of problem. But remember, in my case, I was able to switch from IB to build my tabs through code. If this is not the case with you then you will probably have to find a way to do this entirely using IB. If you already know the way to do this, feel free to share it by commenting below.
Somehow the CoreDataRecipes example off of the apple dev centre has done it but I can’t work out how exactly they have passed the context to the navigation controller. I see in the appdelegate that they have set the managed context for the first controller but that doesn’t seem to work for myself.
Stumped on how to fix this, I’d rather not do it programmatically but I’m starting to think I will have to :S
Thanks! Very simple solution. And you’re right; you saved me hours of looking.