我收到了这个错误:
'+ entityForName:nil不是合法的NSManagedObjectContext参数 搜索实体名称'电影''
每当我尝试将某些内容保存到coreData时,我想知道如何摆脱它。我在线搜索,但看起来大多数答案都是在客观c中,当需要快速解决方案时。如果它有所不同,我在项目创建后手动添加了coreData。确保所有锅炉板代码都被复制到AppDelegate for coreData。这就是数据的保存方式:
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)")
}
}
答案 0 :(得分:0)
我怀疑是什么导致了这个问题,但我相信您需要调用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模型的屏幕截图。