I am starting with Core Data in Swift, and as I saw in many tutorials, everyone is using ManagedObjectContext
only in AppDelegate.swift
.
In my application I would like to use ManagedObjectContext
in multiple views, so I would need some mechanism of sharing that object.
I thought that it would be a good approach to create a class that will manage ManagedObjectContext
everywhere.
I am not sure is it possible that ManagedObjectContext
and other Core data related objects are initialized with singleton and is this even a good approach? Or it is better that I transfer ManagedObjectContext
between every view (which I can't understand why it would be better).
Do you have some advice / suggestion or good demo for usage of Core data?
There are basically three options:
Pass the context from the application delegate object to the initial view controller and then further from source view controller to destination view controller respectively.
Since the application delegate object is accessible from everywhere leave the Core Data stack – as suggested by the template – in AppDelegate
and simply write
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContext
Move the whole Core Data stack into a separate class and use it as singleton
class CoreDataManager: NSObject {
class var sharedManager : CoreDataManager {
struct Singleton {
static let instance = CoreDataManager()
}
return Singleton.instance
}
// MARK: - Core Data stack
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("MyModel", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
...
lazy var managedObjectContext: NSManagedObjectContext = {
...
and call it with
let managedObjectContext = CoreDataManager.sharedManager.managedObjectContext