1

好的,我建立了一个自反关系实体(在我之前发布的 [SO question] 的帮助下1

我相信我设置正确:

在此处输入图像描述

我有一个实体 GroupMember。我创建了与自身的多对多关系。

然后我添加一个实体并创建一个“子”实体并将其设置为关系:

GroupMember *groupMember = [NSEntityDescription insertNewObjectForEntityForName:@"GroupMember" inManagedObjectContext:context];
groupMember.name = @"Ted";

GroupMember *subGroupMember = [NSEntityDescription insertNewObjectForEntityForName:@"GroupMember" inManagedObjectContext:context];
subGroupMember.name = @"sub member bill";

[groupMember addSub_member_relObject:subGroupMember];

然后,我对任何 GroupMember 实体发出获取请求,以查看是否设置了关系。我得到的是:

fetch objects: (
    "<GroupMember: 0x83cf280> (entity: GroupMember; id: 0x98686b0 <x-coredata://D9082F84-03D9-408D-B0DA-5C75C1B905AB/GroupMember/p1> ; data: {\n    \"member_rel\" =     (\n    );\n    name = Ted;\n    \"sub_member_rel\" =     (\n        \"0x989f390 <x-coredata://D9082F84-03D9-408D-B0DA-5C75C1B905AB/GroupMember/p2>\"\n    );\n})",
    "<GroupMember: 0x83cf4a0> (entity: GroupMember; id: 0x989f390 <x-coredata://D9082F84-03D9-408D-B0DA-5C75C1B905AB/GroupMember/p2> ; data: {\n    \"member_rel\" =     (\n        \"0x98686b0 <x-coredata://D9082F84-03D9-408D-B0DA-5C75C1B905AB/GroupMember/p1>\"\n    );\n    name = \"sub member bill\";\n    \"sub_member_rel\" =     (\n    );\n})"
)
2012-12-13 12:08:45.352 [9539:14003] name: Ted
2012-12-13 12:08:45.355 [9539:14003] set: Relationship 'sub_member_rel' on managed object (0x83cf280) <GroupMember: 0x83cf280> (entity: GroupMember; id: 0x98686b0 <x-coredata://D9082F84-03D9-408D-B0DA-5C75C1B905AB/GroupMember/p1> ; data: {
    "member_rel" =     (
    );
    name = Ted;
    "sub_member_rel" =     (
        "0x989f390 <x-coredata://D9082F84-03D9-408D-B0DA-5C75C1B905AB/GroupMember/p2>"
    );
}) with objects {(
    <GroupMember: 0x83cf4a0> (entity: GroupMember; id: 0x989f390 <x-coredata://D9082F84-03D9-408D-B0DA-5C75C1B905AB/GroupMember/p2> ; data: {
    "member_rel" =     (
        "0x98686b0 <x-coredata://D9082F84-03D9-408D-B0DA-5C75C1B905AB/GroupMember/p1>"
    );
    name = "sub member bill";
    "sub_member_rel" =     (
    );
})
)}

A)我不太明白如何阅读这个输出。什么是“带对象”部分?是那个有关系的实体吗?“子会员账单”是否正确设置为子会员关系?

B) 当我尝试取回 groupMember.Sub_member_rel 时,我得到一个 NSSet。我如何遍历这些对象以取回子成员名称(以显示在表格视图中)?

4

1 回答 1

2

A)打印 anNSManagedObject或其关系的输出通常很冗长且有些复杂。在您的情况下,首先打印关系所属的对象。然后是“与对象”部分,它由该特定关系中的对象组成。

B)在多对多关系中,关系类型始终为NSSet. 就像NSArray你可以遍历NSSet这样的:

for (GroupMember *subGroupMember in groupMember.sub_member_rel) {
    // Do something with managedObject
}
于 2012-12-13T20:59:24.740 回答