AppDelegate类型的值没有成员managedObjectContext

时间:2017-05-17 12:33:58

标签: ios swift core-data xcode8 managedobjectcontext

代码

    let managedObjectContext =
        (UIApplication.sharedApplication.delegate
            as! AppDelegate).managedObjectContext

错误:

  • 类型AppDelegate的值没有成员managedObjectContext

我的问题是我想在Xcode 8中使用managedObjectContext,但它说AppDelegate没有这样的成员。我想使用它,因为我想为ios 9创建一个带有核心数据的项目。 我想要managedObjectContext的定义,如果你有

,请发表评论

2 个答案:

答案 0 :(得分:-1)

说明:

  • 错误很明显,它指出AppDelegate没有名为managedObjectContext的属性。检查AppDelegate,看看名称为managedObjectContext的媒体资源是否存在。

参考:

在编写代码之前学习以下内容非常重要:

答案 1 :(得分:-1)

您只需要创建一个刻度为“使用核心数据”的项目,它将在您项目的应用代表中提供。image of project creation and selection of use core data tick mark

    lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
    */
    let container = NSPersistentContainer(name: "temp")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

在app delegate中使用

let context = persistentContainer.viewContext