如何在Xcode 8中使用Swift 3创建managedObjectContext?

阿德玛(Adelmaer):

面临的问题“类型'AppDelegate'的值没有成员'managedObjectContext'在尝试在View Controller中创建新上下文时,在新的Xcode 8(使用Swift 3,iOS 10)中

let context = (UIApplication.shared().delegate as! AppDelegate).managedObjectContext

在Xcode 8中,AppDelegate.swift文件中没有ManagedObjectContext的代码。AppDelegate.swift中的核心数据堆栈代码仅通过以下方式呈现:lazy varpersistentContainer:NSPersistentContainer属性和func saveContext()。没有managedObjectContext属性。

如何在Xcode 8中使用Swift 3创建managedObjectContext,或者也许不需要使用Swift 3来创建它?

詹姆斯·阿莫:

在Swift3中,您可以通过viewContext访问managedObjectContext,如下所示:

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

如果在创建项目时启用了核心数据,则此选项可用。但是,对于要包含核心数据的现有项目,请完成添加核心数据的常规过程,并添加以下代码,这将使您获得

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "you_model_file_name")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error {

            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

您将需要导入CoreData。

注意:对于Swift3,ManagedObject子类是自动生成的。WWDC 2016了解更多

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章