Reputation: 1160
This is my code:
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)
}
}
And this is the error:
-[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'
I cant figure out what's going on. I have 2 entities, Friend and Message. Friend has name and profileImageName as strings attributes and Message has text and date and they both have an inverse relationship. This is as much data as i can give you guys. Please help.
Upvotes: 0
Views: 554
Reputation: 76
Don't use low-level functions like setValue(:forKey:) for NSManagedObject subclasses.
The problem is here:
messageAdagio.setValue("adagio", forKey: "friend")
...
messageGlaive.setValue("glaive", forKey: "friend")
You are trying to set value of type String to object's field of type Friend
Upvotes: 1
Reputation: 1160
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()
This worked. So the difference is instead of .setValue() I just used the attributes of the models.I have no idea what the difference is but after research and research...this is the one that worked. My guess is the structure or type of the data did not match somehow...
Upvotes: 0