我正在尝试将核心数据添加到现有项目中(我正在使用Xcode 11.4.1)。所以我将以下内容添加到我的AppDelegate文件中:
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "DataModel")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
到目前为止,我有以下简单模型:
我已经在我的AppDelegate和ViewController中导入了CoreData。但是,我似乎无法访问此新模型。当我尝试如下创建它的实例时:
let newSheet = RefuelSheet()
我只是收到“无法解析的标识符”错误。
我的理解是,因为我选择了“类定义”,所以相关类将由XCode自动创建,并且我可以访问该对象。
我曾尝试清理该项目并进行测试,但还是没有运气。
I've also checked that the data model file definitely has the same name as the persistent container defined in AppDelegate which it does.
Xcode 11.4
I created a new project and created your xcdatamodel
as you have and Codegen set to Class Definition. The only exception being the Module field in the Data Model Inspector is cleared and set to Global namespace.
After building the project, the RefuelSheet
class was not recognised by the compiler. Likewise following a Clean + Build. However, I closed Xcode and upon reopening and building, the class was recognised.
If that doesn't work, try creating the class manually as well:
Select your xcdatamodel > Editor > Create NSManagedObject Subclass
生成项目,它应该告诉您类被创建两次。现在,删除手动生成的类,然后再次执行Clean + Build。
就我个人而言,我总是对CoreData
类使用手动代码生成器,因为它提供了对Types(尤其是关系)和自定义函数的更细粒度的控制。
另外,创建CoreData
类的实例时,需要使用指定的初始化程序之一,通常是(context:)
:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let moc = appDelegate.persistentContainer.viewContext
let newSheet = RefuelSheet(context: moc)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句