Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding An Item To An NSSet For A Core Data One To Many Relationship

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!

like image 871
Dale Baker Avatar asked Dec 16 '15 12:12

Dale Baker


People also ask

What are relationships in Core Data?

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.

How do you use transformable Core Data?

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.

What is NSSet in Swift?

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.


1 Answers

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")
like image 130
Mundi Avatar answered Nov 30 '22 23:11

Mundi