添加一个项目到一个核心数据一对多关系的NSSet

我有一个核心数据关系,一个实体拥有另一个实体。 据我所知,许多类的每个实例都在NSSet中? 在一个class里面 (?)

我的问题是 – 什么是最好的方式添加到这个集合的项目? 我认为这一定是一个非常普遍的问题 – 但我似乎无法find一个简单的方法。

这是我的尝试:(这一切都来自一个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 } 

其中retrieveValues()只是更新类中的所有coreData值。 TimeSlot是我想要添加的许多对象。

我在最后一行得到一个错误,错误是:“不能调用types为Array的参数为List的types为Set <_>的初始化程序”

我在概念上是错的吗? 谢谢!

你已经宣布timeSlotItemssaveTimeSlot:作为静态,所以我不知道你的意图是在那里。 我怀疑这不是你所需要的。

与Core Data自动运行时生成优化的属性访问器的方式一样,它也为关系生成访问器。

你不会说多对多关系的“一边”是什么名字,但是如果我假设它是类似于Schedule ,其中ScheduletimeSlotItems有多对多的关系叫timeSlotItems ,那么Core Data将运行时 – 为您生成以下访问器:

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

对于一对多这很容易。 只要使用相反的一对一的关系。

 timeSlot.item = self 

对于多对多,我使用这种方便的方法:

 // 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) } } 

这是这样使用的:

 self.addObject(slot, forKey:"timeSlotItems")