解包后,CoreDataStack中的ManagedObjectContext返回nil

时间:2016-04-22 21:59:18

标签: ios xcode swift core-data nsmanagedobjectcontext

我试图牢牢掌握Core Data,并且大部分时间都是如此,尤其是对于子/父上下文和获取结果控制器。但是,我有点卡在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

1 个答案:

答案 0 :(得分:2)

这并不能解决您的问题,但我提供了另一种解决方案。我没有看到您提供的代码有任何问题。看看你以后如何尝试在其他视图控制器中获取CoreDataStack,以及为什么你认为它不会持续存在会很有帮助。

我通常使我的CoreDataStack类只是静态方法和变量的集合。

lazy替换为您static上所有变量的CoreDataStack(所有静态变量都自动延迟)。然后,您希望在应用中的任何位置使用您的上下文:

let ctx = CoreDataStack.context;