我收到此错误:
'+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Movie''
每当我尝试将某些内容保存到 coreData 时,我想知道如何摆脱它。我在网上搜索过,但看起来大多数给出的答案都是在 Objective-C 中,当需要一个快速的解决方案时。如果有什么区别,我会在项目创建后手动添加 coreData 。确保所有样板代码都复制到 CoreData 的 AppDelegate 中。这就是数据的保存方式:
func saveToCoreData(id: NSNumber) {
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
let entity =
NSEntityDescription.entity(forEntityName: "Movie",
in: managedContext)!
let id = NSManagedObject(entity: entity,
insertInto: managedContext)
id.setValue(id, forKeyPath: "id")
do {
try managedContext.save()
savedCoreDataMovieIdArray.append(id)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
最佳答案
我怀疑是什么导致了这个问题,但我相信您需要调用 appDelegate 来保存上下文。只是为了确定导致问题的原因:
func saveToCoreData(id: NSNumber) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Movie", in: managedContext)
let id = NSManagedObject(entity: entity!, insertInto: managedContext)
id.setValue(id, forKeyPath: "id")
do {
try appDelegate.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
如果没有解决,请分享您的 CoreData 模型的屏幕截图。
关于ios - '+实体名称 : nil is not a legal NSManagedObjectContext parameter searching for entity name 'Movie' ',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43057208/