在CoreData中,我已经从Node到Tag定义了一个无序的多对多关系.我创建了一个这样的
Swift实体:
import CoreData
class Node : NSManagedobject {
@NSManaged var tags : Array<Tag>
}
现在我想添加一个Tag到Node的一个实例,像这样:
var node = NSEntityDescription.insertNewObjectForEntityForName("Node",inManagedobjectContext: managedobjectContext) as Node
node.tags.append(tag)
但是,这会失败,并显示以下错误:
Terminating app due to uncaught exception ‘NSinvalidargumentexception’,reason: ‘Unacceptable type of value for to-many relationship: property = “tags”; desired type = NSSet; given type = _TtCSs22ContiguousArrayStorage000000000B3440D4; value = (
“<_TtC8MotorNav3Tag: 0xb3437b0> (entity: Tag; id: 0xb343800 ; data: {…})”
).’
多对多关系的正确类型是什么?
为了能够在Swift中使用一对多的关系,您需要将属性定义为:
class Node: NSManagedobject {
@NSManaged var tags: NSSet
}
如果您尝试使用NSMutableSet更改将不会保存在CoreData中.当然,建议在Node中定义反向链路:
class Tag: NSManagedobject {
@NSManaged var node: Node
}
但是Swift仍然无法在运行时生成动态访问器,因此我们需要手动定义它们.在类扩展中定义它们并放入Entity CoreData.swift文件中非常方便. Bellow是Node CoreData.swift文件的内容:
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)
}
}
用法:
// somewhere before created/fetched node and tag entities node.addTagObject(tag)
重要:为了使其全部工作,您应该验证您的CoreData模型中的实体的类名包括您的模块名称.例如. MyProjectName.Node