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!
Inverse relationships enable Core Data to propagate change in both directions when an instance of either the source or destination type changes. Every relationship must have an inverse. When creating relationships in the Graph editor, you add inverse relationships between entities in a single step.
To implement a Transformable attribute, configure it by setting its type to Transformable and specifying the transformer and custom class name in Data Model Inspector, then register a transformer with code before an app loads its Core Data stack.
NSSet is “toll-free bridged” with its Core Foundation counterpart, CFSet . See Toll-Free Bridging for more information on toll-free bridging. In Swift, use this class instead of a Set constant in cases where you require reference semantics.
For one-to-many this is easy. Just use the reverse to-one relationship.
timeSlot.item = self
For many-to-many I use this convenience method:
// Support adding to many-to-many relationships
extension NSManagedObject {
func addObject(value: NSManagedObject, forKey key: String) {
let items = self.mutableSetValueForKey(key)
items.addObject(value)
}
func removeObject(value: NSManagedObject, forKey key: String) {
let items = self.mutableSetValueForKey(key)
items.removeObject(value)
}
}
which is used like this:
self.addObject(slot, forKey:"timeSlotItems")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With