I'm trying to get a firm grip on Core Data and for the most part everything makes since, especially with child/parent contexts and fetch result controller. However I'm sort of stuck on the CoreDataStack. I'm trying to call the attribute 'context' in the rest of the program. I can print the context in my first view but it doesn't seem to be persisting throughout the app via the navigation bar.
This is CoreDataStack.swift
//exablishes the directory to be used for the stack in SQLite fashion
private lazy var applicationDocumentsDirectory: NSURL = {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
//establishes the managed context by which managed objects interact in reading and writing
lazy var context: NSManagedObjectContext = {
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = self.psc
return managedObjectContext
}()
//establishes the coordinator that connects the managed context with the persistent store
private lazy var psc: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(
managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.modelName)
do {
let options = [NSMigratePersistentStoresAutomaticallyOption : true]
try coordinator.addPersistentStoreWithType( NSSQLiteStoreType, configuration: nil, URL: url, options: options) //establishes the actual persistent store
} catch {
print("Error adding persistent store.")
}
return coordinator
}()
//establishes the object model that interacts with the GUI object data model
private lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = NSBundle.mainBundle().URLForResource(self.modelName, withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
And this is the relevant section in AppDelegate.Swift
let navigationController = window!.rootViewController as! UINavigationController
let listViewController = navigationController.topViewController as! ViewController
listViewController.coreDataStack = coreDataStack
This doesn't really solve your problem, but I provide an alternate solution. I don't see anything wrong with the code you provided. It would be helpful to see how you later try to get the CoreDataStack
in other view controllers, and why you think it's not persisting.
I usually make my CoreDataStack
class just a collection of static methods and variables.
Replace lazy
with static
(all static vars are automatically lazy) for all of the variables on your CoreDataStack
. Then, anywhere in your app you want to use your context:
let ctx = CoreDataStack.context;