如何在Xcode 8中使用Swift 3创建managedObjectContext? [英] How to create managedObjectContext using Swift 3 in Xcode 8?
问题描述
面对问题类型AppDelegate的值没有成员managedObjectContext在新的Xcode 8(使用Swift 3,iOS 10)当尝试在View Controller中创建新的上下文
let context =(UIApplication.shared()。delegate as!AppDelegate).managedObjectContext
在Xcode 8中没有AppDelegate.swift文件中的managedObjectContext的代码。AppDelegate.swift中的Core数据栈代码只有:lazy var persistentContainer:NSPersistentContainer property和func saveContext()。没有managedObjectContext属性。
如何使用Xcode 8中的Swift 3创建managedObjectContext)或者没有必要使用Swift 3?
$ b $在Swift3中,您可以通过viewContext访问managedObjectContext<$> c $ c> let context =(UIApplication.shared.delegate as!AppDelegate).persistentContainer.viewContext
如果在创建项目时已启用Core数据,则此选项可用。但是,对于要包含核心数据的现有项目,请执行添加核心数据的正常过程,并添加以下代码,以便获取
lazy var persistentContainer:NSPersistentContainer = {
let container = NSPersistentContainer(name:you_model_file_name)
container.loadPersistentStores(completionHandler:{(storeDescription,error )in
if let = error {
fatalError(未解决的错误\(错误),\(error.userInfo))
}
} )
return container
}()
您需要导入CoreData 。
注意:对于Swift3,ManagedObject子类是自动生成的。
查看更多 WWDC 2016
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
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.
How to create managedObjectContext using Swift 3 in Xcode 8) or maybe there is no need to do it using Swift 3 ?
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
}()
You will need to import the CoreData.
Note: For Swift3, the ManagedObject Subclass are generated automatically. See more from WWDC 2016
这篇关于如何在Xcode 8中使用Swift 3创建managedObjectContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!