我试图牢牢地掌握核心数据,并且在大多数情况下,从那以后,所有的事情都会发生,特别是对于子/父上下文和fetch result controller。不过,我有点拘泥于CoreDataStack。我试图在程序的其余部分调用“context”属性。我可以在第一个视图中打印上下文,但它似乎不会通过导航栏在整个应用程序中持久化。
我是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)!
}()
这是AppDelegate.Swift中的相关部分
let navigationController = window!.rootViewController as! UINavigationController
let listViewController = navigationController.topViewController as! ViewController
listViewController.coreDataStack = coreDataStack
最佳答案
这并不能真正解决你的问题,但我提供了另一种解决方案。我看你提供的代码没有什么问题。这将有助于了解以后如何在其他视图控制器中获取CoreDataStack
,以及为什么您认为它不会持续。
我通常将CoreDataStack
类设置为静态方法和变量的集合。
将lazy
替换为static
(所有静态变量都自动变懒)用于CoreDataStack
上的所有变量。然后,在你的应用程序中,你想使用你的上下文的任何地方:
let ctx = CoreDataStack.context;