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

て烟熏妆下的殇ゞ 提交于 2019-12-21 20:00:30

问题


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!


回答1:


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")



回答2:


You've declared both timeSlotItems and saveTimeSlot: 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, where Schedule has a to-many relation to TimeSlot called timeSlotItems, then Core Data will runtime-generate the following accessors for you:

class Schedule: NSManagedObject {
    @NSManaged public var timeSlotItems: Set<TimeSlot>
    @NSManaged public func addTimeSlotItemsObject(value: TimeSlot)
    @NSManaged public func removeTimeSlotItemsObject(value: TimeSlot)
    @NSManaged public func addTimeSlotItems(values: Set<TimeSlot>)
    @NSManaged public func removeTimeSlotItems(values: Set<TimeSlot>)
}


来源:https://stackoverflow.com/questions/34311872/adding-an-item-to-an-nsset-for-a-core-data-one-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!