I have a core data relationship where one entity holds many of another entity. As far as I am aware each instance of the many class is held inside an NSSet? inside the one class. (?)
My question is - what is the best way to add items to this set? I figure this must be a very common problem - but I cannot seem to find an easy method.
This is my attempt: (This is all taken from the one class)
static var timeSlotItems: NSSet? //The Set that holds the many?
...
static func saveTimeSlot(timeSlot: TimeSlot) { //TimeSlot is the many object
retrieveValues()
var timeSlotArray = Array(self.timeSlotItems!)
timeSlotArray.append(timeSlot)
var setTimeSlotItems = Set(timeSlotArray)
self.timeSlotItems = setTimeSlotItems // This is the error line
}
Where retrieveValues() just updates all the coreData values in the class. TimeSlot is the many object which I want to add.
I get an error on the last line, the error is: "cannot invoke initializer for type Set<_> with an argument of list of type Array"
Am I conceptually wrong at all? Thanks!
For one-to-many this is easy. Just use the reverse to-one relationship.
For many-to-many I use this convenience method:
which is used like this:
Nowadays it is this easy...
For a to-many item named say "Reply", CoreData knows to add a call "addToReplys".
Hence...
so it's just
Full example
You've declared both
timeSlotItems
andsaveTimeSlot:
as static, so I'm not sure what your intention is there. I suspect it's not what you need.In the same way that Core Data automatically runtime-generates optimized accessors for attributes, it also generates accessors for relations.
You don't say what the name of the "one" side of the to-many relation is, but if I assume that it's something like
Schedule
, whereSchedule
has a to-many relation toTimeSlot
calledtimeSlotItems
, then Core Data will runtime-generate the following accessors for you: