2016-12-11 297 views
0

時,這是我的代碼:崩潰存儲到核心數據

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]: unrecognized selector sent to instance 0x600000051040 2016-12-11 10:22:34.834 Chat App - Core Data Demo[21356:1755677] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Swift._NSContiguousString managedObjectContext]: unrecognized selector sent to instance 0x600000051040'

我無法弄清楚發生了什麼事情。我有2個實體,朋友和消息。朋友的姓名和profileImageName作爲字符串屬性,而消息具有文本和日期,並且它們都有相反的關係。這是儘可能多的數據,我可以給你們。請幫忙。

+1

我的猜測是'viewcontext'吸氣劑是做一些它不應該。在那裏放置一些休息處,找出爲什麼你可能會得到該代碼中的字符串 –

回答

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()我只是使用了模型的屬性。我不知道有什麼區別,但經過研究和研究......這是一個有效的工具。我的猜測是數據結構或類型不匹配莫名其妙...

+1

有一個**巨大的**區別。你舊的messageAdagio.setValue(「adagio」,forKey:「friend」)代碼試圖給'friend'屬性分配一個String。在您在此答案中發佈的代碼中,您將「朋友」對象分配給「朋友」屬性。使用'setValue'可以使用'messageAdagio.setValue(adagio,forKey:「friend」)''。 – rmaddy

1

不要使用低級別的功能,如的setValue(:forKey :)NSManagedObject子類。

的問題是在這裏:

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

您試圖設置類型字符串的值對象類型的領域朋友

+0

它會不會拋出錯誤?我明白你的意思,但它並沒有給我一個錯誤。 –

+0

是的,它沒有。實際上,你可以在NSManagedObjectContext中用你的NSManagedObjects做一些瘋狂的事情。像做瘋狂的關係一樣,將* nil *設置爲非可選字段,設置負值兩個字段,這應該是NSManagedModel的正面原因。 – Simbos

+0

但是,只有當您存儲/保存/合併您的上下文時纔會完成所有必要的檢查 – Simbos