我尝试构建一个内部带有CoreData的框架。我用来自iOS 10文件的容器初始化CoreData堆栈是这样的
class CoreDataStack {
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "MySDK")
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)")
}
}
}
func insert(check: Check) {
guard let entityDescription = NSEntityDescription.entity(forEntityName: "CheckEntity", in: persistentContainer.viewContext) else { return }
let managedObject = CheckEntity(entity: entityDescription, insertInto: persistentContainer.viewContext)
managedObject.total = Int64(check.total)
if let payment = check.payment {
guard let paymentEntity = NSEntityDescription.entity(forEntityName: "PaymentEntity", in: persistentContainer.viewContext) else { return }
let paymentEntityObject = PaymentEntity(entity: paymentEntity, insertInto: persistentContainer.viewContext)
paymentEntityObject.amount = Int64(payment.amount)
managedObject.addToPayment(paymentEntityObject)
}
for item in check.items {
guard let entityDescription = NSEntityDescription.entity(forEntityName: "CheckItemEntity", in: persistentContainer.viewContext) else { return }
let printerCheckItemEntity = CheckItemEntity(entity: entityDescription, insertInto: persistentContainer.viewContext)
printerCheckItemEntity.uuid = item.uuid
managedObject.addToItems(printerCheckItemEntity)
}
saveContext()
}
}
问题是,当我尝试调用方法insert
时会崩溃
2019-01-14 18:30:04.115533 + 0300 MySDKTest [20465:33363837] *** 由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'+ entityForName:nil不是 合法的NSManagedObjectContext参数搜索实体名称 'CheckEntity'
我在做什么错了?