This is how I'm currently doing it but I'm wondering if this is how Apple suggests. I've read some debates about that.
let appDelegate : AppDelegate = NSApplication.sharedApplication().delegate as AppDelegate
if let moc = appDelegate.managedObjectContext {
// do stuff here
}
So that's just to get it from the AppDelegate
to the first viewController
. From there I'm guessing that using segues
is the way to go to pass around the managedObjectContext
?
Using the above code is pretty annoying because I'm typing that into every method in the viewController
that needs the MOC
. It's even more annoying when I have a function with a return
statement and all my code that uses the MOC
is inside the body of the if statement
since that creates errors stating that there is/may not be a return
. Is there a better way to do that, like make it more global?
EDIT:
My ViewController.swift file has this header:
import Cocoa
class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
and contains a Table View
My AppDelegate.swift file has:
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
Apple sample code stores and creates the Core Data stack in the app delegate, but that doesn't mean it's right. In fact, it's entirely wrong. The app delegate shouldn't own the data store. Apple does it, and most people follow along, because it's convenient. You should really have a custom class which owns and creates the Core Data stack.
This custom class needs to be instantiated somewhere, that could be in the app delegate and then passed to your root view controller, or it could be in the root view controller itself. This custom class could also be a singleton (because you don't want multiple instances of it).
Each view controller should have a public property for the MOC which is set by its creator (part of the segue code). In this way each controller isn't going and getting the MOC, the MOC dependency is being injected. This helps keep the relationships clean and aids in unit testing. You also don't need the let
to check you got the MOC back - if it isn't there it's a development issue (and if it couldn't be created you should never have created / pushed the view controller...).