【问题标题】:Getting nil value from entity in core data从核心数据中的实体获取零值
【发布时间】:2018-07-27 03:59:48
【问题描述】:

我正在关注 raywenderlich 的 Core Data 教程:Tutorial

我面临的问题是在这个 sn-p 代码中:

let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)!
let person = NSManagedObject(entity: entity,insertInto: managedContext)

实体值返回nil,应用程序崩溃。有没有什么我错过了,因为我已经尝试了 3-4 次但仍然是同样的问题

【问题讨论】:

  • 与问题无关,但千万不要强制解包,至少你的应用不会崩溃。
  • 在使用核心数据时还要检查数据故障..

标签: ios swift core-data nsmanagedobject


【解决方案1】:

如果你说你说的是正确的(在提到的行上崩溃),那么数据模型中不存在 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)")
  }
}

这表明您还必须检查 name 实体上的 name 属性:

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多