How the using CoreDataStack in complex situation?

Recently I use CoreData in my App, and I have a little question about CoreDataStack and ManagedContext.

I have a CoreDataStack class just like in Chapter.3.

  1. Should I control there is only one CoreDataStack instance in my App?

  2. If not, what circumstances will there be multiple contexts object?

  3. Can I make the Stack class as SingletonClass? and then I can fetch Context object just like

    CoreDataStack.sharedInstance.context!.fetch(fetchRequest)

, so don’t need to pass the context Object from one ViewController. Is its solution good or bad?

@yangzai360 Thanks very much for your question! I think you’ve misunderstood the purpose of what the CoreDataStack (CDS) is intended for. The CDS is meant to initialize the components of Core Data (i.e. ManagedObjectModel, ManagedObjectContext, NSPersistentStore, NSPersistentStoreCoordinator). Once these objects have been initialized, the MOC is what you would use for performing your Core Data functions throughout your app, which is why this object is what gets passed from View Controller to ViewController. So to answer your questions:

  1. Yes, there should be only ONE instance of the CDS which gets called at the launch of the app, and then passes the MOC to the RootViewController (i.e. the first ViewController) in your app. However, you shouldn’t be using the instance of the CDS throughout the app, but rather, you should be using the ManagedObjectContext that you generate from it, and then pass around.

  2. Having a child ManagedObjectContext in your app does not mean you need another instance of your CDS. If you have our Core Data by Tutorials book, you should take a look at Chapter 9 which we devote entirely to multiple managed objects contexts :slight_smile:

  3. See my answer to question 1. Don’t worry so much on the instances of the CDS, but rather, focus on using the ManagedObjectContext, and the Core Data functions. Having the MOC is what you need so focus on using it. Singletons are not a very good idea since your instance lives “forever” throughout the lifecycle of the app. It is better to work with an instance of the ManagedObjectContext as shown in chapter 3, which you then pass around to other View Controllers as needed. This forces you to design a well constructed app, and with this approach, you minimize your app’s use of resources. Having a Singleton instance makes things convenient, but doesn’t properly use resources.

I hope this helps!

Many thanks for you clarification.

I was also wondering question 1 too. Although I understand your answer to it, I can see that in the Core Data by Tutorials book, we pass sometimes the CoreDataStack instance rather than its managed object context. Any idea why?

Many thanks