【问题标题】:Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSEntityDescription 0x7fc863f27230> setValue:forUndefinedKey:]由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[<NSEntityDescription 0x7fc863f27230> setValue:forUndefinedKey:]
【发布时间】:2017-02-19 17:14:19
【问题描述】:

我尝试学习完全基础的核心数据。不幸的是这个错误抛出

由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[setValue:forUndefinedKey:]:此类不符合键标题的键值编码。

所以到这个时候应用程序终止。

以 NSException 类型的未捕获异常终止

我该怎么办?我错过了什么谢谢

这是视图控制器中的代码

 @IBAction func createMangeObjectBtn(sender: AnyObject) {

        let appDelegate  = UIApplication.sharedApplication().delegate as! AppDelegate

        let context  =  appDelegate.managedObjectContext

        let entityForName =  NSEntityDescription.entityForName("Book", inManagedObjectContext: context)

        entityForName?.setValue("iOS Programming", forKey: "title")
        entityForName?.setValue("12/12/12", forKey: "publishDate")
        entityForName?.setValue("NH001", forKey: "code")
        entityForName?.setValue("tolight", forKey: "author")


        do{
           try context.save()
            print("saved")
        }
        catch{
          print("something happend")
        }

    }

这是模型:

【问题讨论】:

    标签: ios swift core-data


    【解决方案1】:

    你的代码

    let entityForName =  NSEntityDescription.entityForName("Book", inManagedObjectContext: context)
    

    创建一个NSEntityDescription 而不是该实体的对象。

    你想要的是

    let book = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext: context)
    book.setValue("iOS Programming", forKey: "title")
    // ...
    

    或者更好的是,为实体创建一个NSManagedObject 子类 并直接使用属性访问器:

    let book = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext: context)
    book.title = "iOS Programming"
    // ...
    

    【讨论】:

      【解决方案2】:

      您在这里创建的是NSEntityDescription 而不是NSManagedObject。实体描述描述了数据库条目的字段和类型。它本身不是数据库条目。

      class func entity(forEntityName entityName: String, in context: NSManagedObjectContext) -&gt; NSEntityDescription?

      要创建 Book 的实例,即数据库中的 1 条记录,您需要获取该描述并将其传递给 init 方法

      init(entity: NSEntityDescription, insertInto: NSManagedObjectContext?)

      所以

      let newBook = NSManagedObject(entityForName,insertInto:context)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-17
        • 2012-01-04
        • 2016-08-20
        相关资源
        最近更新 更多