I am a little confused about where to setup my Core data Stack. In the Appdelegate or using a shared instance of UIManagedDocument, described here?: http://adevelopingstory.com/blog/2012/03/core-data-with-a-single-shared-uimanageddocument.html
Right now I have by core data stack setup in my AppDelegate and I am passing my MOC around between the viewcontrollers. But would it be better to migrate to UIManagedDocument and make a shared Instance, so I don't have to pass the MOC around all the time? And also because its newer?
UIManagedDocument
is used to sync data (typically files) to iCloud. It is only tangentially related to Core Data.Core Data setup is typically done in the
AppDelegate
so there is nothing wrong with what you are doing there. In fact, if you create a new project using Core Data that is how the Xcode template will do it.You usually do not need to pass your
ManagedObjectContext
around from viewcontroller to viewcontroller. It is better to create a singleton Data Access layer which can provide context anywhere in your app. There are some cases where you might want to have a private MOC for a viewcontroller, but not very often.Here's some code to create a singleton DataAccessLayer:
DataAccessLayer.h
DataAccessLayer.m
Any time you need context, you can grab it using:
This design generally works well.
NSManagedObjectContext
is a very lightweight object, so there isn't a real performance penalty keeping it around. However, if you need to do Core Data stuff on other threads, the design needs to change a bit. From Apple's docs:The singleton method above is very slick. A much simpler approach is to treat the appDelegate as a singleton, which it is. Create the properties in your appDelegate then a version of the following line will retrieve the one you want. For example to retrieve the moc