【问题标题】:NSEntityDescription is nilNSEntityDescription 为零
【发布时间】:2016-07-12 21:26:58
【问题描述】:

我的变量entityDescription 似乎为零,所以我在编译时遇到了致命错误。有谁知道解决方案? persistentContainer 在同一个类 (AppDelegate) 中声明。

let entityDescription = NSEntityDescription.entity(forEntityName: "Person", in: self.persistentContainer.viewContext)
let newPerson = NSManagedObject(entity: entityDescription!, insertInto: self.persistentContainer.viewContext)
newPerson.setValue("Thomas", forKey: "first")

【问题讨论】:

    标签: ios swift core-data swift3


    【解决方案1】:

    请检查方法名称,以下代码为我创建了一个 NSEntityDescription 对象。

    let desc:NSEntityDescription? = NSEntityDescription.entityForName("Person", inManagedObjectContext: self.managedObjectContext);
    print(desc)
    

    【讨论】:

      【解决方案2】:

      您应该看看 Core Data Xcode 模板。 (选择新项目,检查,Master/Detail,检查 Core Data。)在 Swift 3 中,您将创建一个新对象,例如使用有效的托管对象上下文。

      let newPerson = Person(context: context)
      newPerson.first = "Thomas"
      

      【讨论】:

      • 这仅适用于 iOS 10,对于低于该版本的版本,您应该查看 Arun EA 的回复:stackoverflow.com/a/38344166/2452039
      • 不,API语法不同,原理与多年前的Core Data版本相同。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      相关资源
      最近更新 更多