Reputation: 67
Here's my medicine object class and extension:
import Foundation
import CoreData
class Medicine: NSManagedObject {
@NSManaged var alarms: NSSet
}
-
import Foundation
import CoreData
extension Medicine {
@NSManaged var name: String?
@NSManaged var dosage: String?
@NSManaged var type: String?
@NSManaged var image: NSData?
func addAlarmObject(value:Alarm) {
let items = self.mutableSetValueForKey("alarms")
items.addObject(value)
}
func removeDeleteObject(value:Alarm) {
let items = self.mutableSetValueForKey("alarms")
items.removeObject(value)
}
}
My alarm object:
import Foundation
import CoreData
extension Alarm {
@NSManaged var time: String?
@NSManaged var weekdays: String?
@NSManaged var isOwnedByMedicine: Medicine?
}
Screenshot of my data models and their relationship:
FINALLY, here is what I'm trying to do:
let predicate = NSPredicate(format: "name == %@", currentMedicine)
let fetchRequest = NSFetchRequest(entityName: "Medicine")
fetchRequest.predicate = predicate
var fetchedCurrentMedicine:Medicine!
do {
let fetchedMedicines = try managedContext.executeFetchRequest(fetchRequest) as! [Medicine]
fetchedCurrentMedicine = fetchedMedicines.first
} catch {
}
//add all the alarms to the Medicine class
for alarmString in alarmList{
let entity = NSEntityDescription.entityForName("Alarm", inManagedObjectContext: managedContext)
let alarm = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) as! Alarm
alarm.setValue("test", forKey: "weekdays")
alarm.setValue(String(alarmString), forKey: "time")
fetchedCurrentMedicine.addAlarmObject(alarm)
}
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
It keeps failing at
fetchedCurrentMedicine.addAlarmObject(alarm)
and I get the error:
"'NSInvalidArgumentException', reason: 'NSManagedObjects of entity 'Medicine' do not support -mutableSetValueForKey: for the property 'alarms''"
Any idea where I may have messed up or gotten the schema of my data models wrong? Much appreciated.
Upvotes: 0
Views: 430
Reputation: 190
On your data model screen alarms
relation of Medicine
model is to one. Perhaps medicines
relation of Alarm
model is to-many.
Anyway try to set to-many relation type for alarms
in the data model inspector.
Upvotes: 2