【发布时间】:2020-01-18 12:38:09
【问题描述】:
我正在尝试使用 Core Data 将数据保存在本地存储中,但出现此错误:
任何模型中都没有 NSEntityDescriptions 声明 NSManagedObject 子类 'TrackItem' 所以 +entity 很困惑。你有没有加载你的 NSManagedObjectModel 了吗?
@IBAction func AddTrack(_ sender: Any) {
print("I made it to AddTrack§§§§§")
let Trackitem = TrackItem(context: PersistenceService.context)
Trackitem.kms = Int32(kmsField!.text!)!
Trackitem.liters = Float(litersField!.text!)!
Trackitem.date = textFieldPicker!.text!
PersistenceService.saveContext()
}
这是保存按钮的功能。知道我用实体及其属性和 CreateNSObject 制作了一个 CoreData 模型......并且我有模型的类和扩展。但是在输入字段中添加一些内容并尝试保存应用程序后停止工作并给我这个错误。
import Foundation
import CoreData
class PersistenceService {
private init() {
}
static var context:NSManagedObjectContext{
return persistentContainer.viewContext
}
// MARK: - Core Data stack
static var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "FillMyTank")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
static func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
【问题讨论】:
-
问题很可能出在 PersistenceService 中。
-
我添加了持久化服务,你看出什么问题了吗?
-
没什么明显的。仔细检查型号名称是否拼写正确。您是否重命名了模型本身或任何实体之类的内容,这可能是个问题。