存储到Core Data时崩溃

时间:2016-12-11 18:36:41

标签: ios core-data swift3 ios10

这是我的代码:

func storingMessage() {

let appDelegate = UIApplication.shared.delegate as! AppDelegate

let context = appDelegate.persistentContainer.viewContext

let adagio = NSEntityDescription.insertNewObject(forEntityName: "Friend", into: context)
adagio.setValue("Adagio", forKey: "name")
adagio.setValue("adagio", forKey: "profileImageName")

let messageAdagio = NSEntityDescription.insertNewObject(forEntityName: "Message", into: context)
messageAdagio.setValue("adagio", forKey: "friend")
messageAdagio.setValue("This is boring....", forKey: "text")
messageAdagio.setValue(NSDate(), forKey: "date")

let glaive = NSEntityDescription.insertNewObject(forEntityName: "Friend", into: context)
glaive.setValue("Glaive", forKey: "name")
glaive.setValue("glaive", forKey: "profileImageName")

let messageGlaive = NSEntityDescription.insertNewObject(forEntityName: "Message", into: context)
messageGlaive.setValue("glaive", forKey: "friend")
messageGlaive.setValue("I will cut you to pieces", forKey: "text")
messageGlaive.setValue(NSDate(), forKey: "date")

do {

    try context.save()
    print("SAVED!!!!")

} catch let err {

    print(err)

}

}

这就是错误:

  

- [Swift._NSContiguousString managedObjectContext]:无法识别的选择器发送到实例0x600000051040 2016-12-11 10:22:34.834聊天   应用程序 - 核心数据演示[21356:1755677] ***终止应用程序由于   未捕获的异常'NSInvalidArgumentException',原因:   ' - [Swift._NSContiguousString managedObjectContext]:无法识别   选择器发送到实例0x600000051040'

我无法弄清楚发生了什么。我有2个实体,朋友和消息。 Friend将name和profileImageName作为字符串属性,Message包含文本和日期,它们都具有反向关系。这是我能给你们的数据。请帮忙。

2 个答案:

答案 0 :(得分:1)

不要为 NSManagedObject 子类使用 setValue(:forKey :) 等低级函数。

问题在于:

messageAdagio.setValue("adagio", forKey: "friend")
...
messageGlaive.setValue("glaive", forKey: "friend")

您正尝试将字符串类型的值设置为朋友

类型的对象字段

答案 1 :(得分:0)

let adagio = NSEntityDescription.insertNewObject(forEntityName: "Friend", into: context) as! Friend
        adagio.name = "Adagio"
        adagio.profileImageName = "adagio_photo"

        //setting up the message as a Message() type and filling in the parameters
        let messageAdagio = NSEntityDescription.insertNewObject(forEntityName: "Message", into: context) as! Message
        messageAdagio.friend = adagio
        messageAdagio.text = "This is boring...."
        messageAdagio.date = NSDate()

这很有用。所以区别于.setValue()我只是使用了模型的属性。我不知道有什么区别,但经过研究和研究......这是有效的。我的猜测是数据的结构或类型在某种程度上不匹配......