To be able to work with one-to-many relationship in Swift you need to define property as:
class Node: NSManagedObject {
@NSManaged var tags: NSSet
}
If you try to use NSMutableSet
changes will not be saved in CoreData. And of course it is recommended to define reverse link in Node
:
class Tag: NSManagedObject {
@NSManaged var node: Node
}
But still Swift cannot generate dynamic accessors in runtime, so we need to define them manually. It is very convenient to define them in class extension
and put in Entity+CoreData.swift
file. Bellow is content of Node+CoreData.swift
file:
extension Node {
func addTagObject(value:Tag) {
var items = self.mutableSetValueForKey("tags");
items.addObject(value)
}
func removeTagObject(value:Tag) {
var items = self.mutableSetValueForKey("tags");
items.removeObject(value)
}
}
Usage:
// somewhere before created/fetched node and tag entities
node.addTagObject(tag)
Important: To make it all work you should verify that class names of entities in you CoreData model includes your module name. E.g. MyProjectName.Node
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…