我正在遵循raywenderlich的核心数据教程:Tutorial
我面临的问题是,在这段代码中:
let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)!
let person = NSManagedObject(entity: entity,insertInto: managedContext)
实体值返回nil
,应用程序崩溃。有没有因为我尝试了3-4次但仍然是同样的问题而错过了什么?
发布于 2018-02-16 17:53:31
如果您说您所说的是正确的(在提到的行上崩溃),那么Person实体就不存在于数据模型中。
请验证模型中是否存在该人员:
同样,在链接教程之后,我怀疑您正在调用save方法,如下所示:
func save(name: String) {
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
// 1
let managedContext =
appDelegate.persistentContainer.viewContext
// 2
let entity =
NSEntityDescription.entity(forEntityName: "Person",
in: managedContext)!
let person = NSManagedObject(entity: entity,
insertInto: managedContext)
// 3
person.setValue(name, forKeyPath: "name")
// 4
do {
try managedContext.save()
people.append(person)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
这意味着您还必须检查Person
实体上的name
属性:
我希望这对你有帮助。
https://stackoverflow.com/questions/48823447
复制相似问题