4

I put the core data stack in its own file as shown below. I read that using dependency injection is the best way to pass the managed object context. So in each of a handful of VCs, I declare the following property:

var managedObjectContext: NSManagedObjectContext?

Now, the tricky part is getting the moc from my stack to the different VCs. Which seems like a great place for a singleton, but assuming that's a bad idea, I guess I would use the code below in CoreDataStack:

let controller = self.window!.rootViewController as! ViewController
let context = self.persistentContainer.viewContext
controller.managedObjectContext = context   

But that leaves me with a few questions:
1) Where in CoreDataStack should I include the code above? In the App Delegate it would go in didFinishLaunchingWithOptions, but that's not really an option now.
2) Writing the above code for every single vc that needs a context seems bad. I guess I could loop through all the VCs. I've seen the moc passed using didSet too, but that doesn't seem quite right either.

CoreData Stack

class CoreDataStack {    
lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "Model")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
         if let error = error as NSError? {
             fatalError("Unresolved error \(error), \(error.userInfo)")
         }
     })
     return container
}()

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}
squarehippo10
  • 1,855
  • 1
  • 15
  • 45
  • I will happily upvote and heed the advice of any answer which explains to me why it is such a bad idea to just be done with it and shamelessly use a singleton for the *view* managed object context in simple iOS apps. I typically make it a property of the app delegate. – Jerry Krinock Apr 27 '19 at 22:16
  • Instead of passing contexts, I would pass `CoreDataStack`. I would declare it in the topmost view controller and pass it down to other view controllers from there. Couldn't you do that? I wouldn't set the context on a view controller from within `CoreDataStack`, that seems like a violation of of encapsulation. – nambatee May 02 '19 at 02:57
  • To be honest, I figured out how to use dependency injection in about 80% of my project, but really struggled after that. So I ended up going back to using a singleton for now. I do plan to revisit this question soon and appreciate the help. – squarehippo10 May 02 '19 at 07:25

0 Answers0