How to get managedObjectContext for viewController other than getting it from appDelegate?

后端 未结 2 2125
后悔当初
后悔当初 2020-12-02 17:53

Recently I came to know that \"You really shouldn\'t be calling down to the AppDelegate to get the managed object context\". Apple also has put this recommendation into thei

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 17:59

    The singleton approach has worked best for me when it comes to grabbing my Managed Object Context. It really depends on the complexity of your app, but in my case I typically keep one Managed Object Context and work with temporary nested contexts when I need to make changes.

    By using a singleton-based "DataManager" class that contains all the Core Data initialization methods with public references to the the Managed Object Model and Context I am able to get to the data by importing my "DataManager.h" class and making calls to the singleton:

    // I have a method to create an object that requires the Manage Object Context, so I call it from the DataManager singleton
    SomeObject *newObject = [SomeObject createObjectInContext:[[DataManager sharedInstance] managedObjectContext]];
    
    // I have a method in DataManager to save the context
    [[DataManager sharedInstance] saveContext];
    

    That is actually the simplified version. I typically use nested Managed Object Contexts so that my main Managed Object Context is not modified until that addition or modification of a Managed Object is confirmed by the user. That complexity can all be contained in the "DataManager" class.

    This is slightly off-topic, but in case you need to learn more about nested contexts: I had serious issues when NOT using nested contexts to make changes to the main Managed Object Context. This article, while some of it went over my head, helped me understand and implement nested contexts:

    http://www.cocoanetics.com/2012/07/multi-context-coredata/

提交回复
热议问题