如何在 Swift 中定义 CoreData 关系? [英] How to define CoreData relationship in Swift?
问题描述
在 CoreData 中,我定义了一个从 Node
到 Tag
的无序对多关系.我已经创建了一个这样的 Swift 实体:
In CoreData, I have defined an unordered to-many relationship from Node
to Tag
. I've created an Swift entity like this:
import CoreData
class Node : NSManagedObject {
@NSManaged var tags : Array<Tag>
}
现在我想给 Node
的一个实例添加一个 Tag
,像这样:
Now I want to add a Tag
to an instance of Node
, like this:
var node = NSEntityDescription.insertNewObjectForEntityForName("Node", inManagedObjectContext: managedObjectContext) as Node
node.tags.append(tag)
但是,这失败并出现以下错误:
However, this fails with the following error:
由于未捕获的异常NSInvalidArgumentException"而终止应用程序,原因:对多关系的值类型不可接受:属性 =标签";所需类型 = NSSet;给定类型 = _TtCSs22ContiguousArrayStorage000000000B3440D4;价值 = (<_TtC8MotorNav3Tag:0xb3437b0>(实体:标签;id:0xb343800;数据:{...})").'
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: {...})" ).'
多对多关系的正确类型是什么?
What is the correct type for to-many relationships?
推荐答案
为了能够在 Swift 中处理一对多关系,您需要将属性定义为:
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
}
如果您尝试使用 NSMutableSet
更改将不会保存在 CoreData 中.当然推荐在Node
中定义反向链接:
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
}
但是 Swift 仍然无法在运行时生成动态访问器,因此我们需要手动定义它们.在extension
类中定义它们并放入Entity+CoreData.swift
文件中非常方便.下面是Node+CoreData.swift
文件的内容:
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)
}
}
用法:
// somewhere before created/fetched node and tag entities
node.addTagObject(tag)
重要提示:要使这一切正常工作,您应该验证 CoreData 模型中实体的类名称是否包含您的模块名称.例如.MyProjectName.Node
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
这篇关于如何在 Swift 中定义 CoreData 关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!