Chapter 2 coreDataStack without VC

Hi,
Chapter 2 assumes that all data operations are occurring in a View Controller but I’m putting all of my data operations in its own file and class. Any ideas on how to pass the managedContext in AppDelegate to a regular class file as opposed to a viewcontroller? If it’s covered in a later chapter, then feel free to just point me there. Thanks.

If the way you have decided to do it is difficult, that might be a sign that you should not do it that way…

The UIViewController is a very convenient place to do these kind of operations because it is the main handler of UI interactions and is often the top-level object in the navigation stack. A common pattern is to pass the managedObjectContext from the AppDelegate to the first view controller and from there to every child view controller and that works pretty well. I usually give each UIViewController a “moc” member for the managedObjectContext when I need to pass it around like this.

Now although that’s the normal pattern, your objects which are not UIViewControllers have to be created somewhere. Can you not pass the moc from the view controller that will create your object?

@scottmetro. I agree with @aeberbach’s approach. Since you are building for an iOS device, if you insist on doing your Core Data activity in a class outside of a ViewController, then my suggestion would be to pass the reference to the Managed Object Context (MOC) from the AppDelegate to the RootViewController, and then from there, pass the MOC to whichever file/class you plan to use it. That would honestly be the best approach for what your suggesting IMHO.

I hope that helps.

All the best!