在新的 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?
发布评论