如何在 Xcode 8 中使用 Swift 3 创建 managedObjectContext? [英] How to create managedObjectContext using Swift 3 in Xcode 8?

查看:13
本文介绍了如何在 Xcode 8 中使用 Swift 3 创建 managedObjectContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Facing issue "Value of type 'AppDelegate' has no member 'managedObjectContext' In new Xcode 8 (using Swift 3, iOS 10) when trying to create new context in View Controller

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

在 Xcode 8 中,AppDelegate.swift 文件中没有 managedObjectContext 的代码.AppDelegate.swift 中的核心数据堆栈代码仅提供:lazy var persistentContainer: NSPersistentContainer 属性和 func saveContext () .没有 managedObjectContext 属性.

In Xcode 8 there is no code for managedObjectContext inside AppDelegate.swift file. Core Data stack code inside AppDelegate.swift presented only with: lazy var persistentContainer: NSPersistentContainer property and func saveContext () . There is no managedObjectContext property.

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

How to create managedObjectContext using Swift 3 in Xcode 8) or maybe there is no need to do it using Swift 3 ?

推荐答案

在 Swift3 中,您可以通过 viewContext 访问 managedObjectContext 为

In Swift3, you can access the managedObjectContext via the viewContext as

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

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

This option is available if Core data was enabled when creating the project. However, for existing project that you want to include core data, go through the normal process of adding the core data and add the following code which will allow you to get the

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.

You will need to import the CoreData.

注意:对于 Swift3,ManagedObject 子类是自动生成的.查看更多来自 WWDC 2016

Note: For Swift3, the ManagedObject Subclass are generated automatically. See more from WWDC 2016

这篇关于如何在 Xcode 8 中使用 Swift 3 创建 managedObjectContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆