使用关系存档Core Data实体

时间:2013-03-23 06:28:43

标签: cocoa core-data

我希望能够支持复制和粘贴显示核心数据实体的tableview行。该实体具有一个属性和两个关系。当我使用Apple推荐的词典存档技术(来自'NSPersistentDocument Core Data Tutorial')时,我发现关系会引发错误。以下是出现问题的基本代码:

for (id sectionObject in selectedSectionsArray){
    NSDictionary *thisDictionary = [sectionObject dictionaryRepresentation];   // 'sectionObject' has 1 attribute and 2 relationships (one-to-many)
    [copyObjectsArray addObject:[sectionObject dictionaryRepresentation]];
}
NSPasteboard *generalPasteboard = [NSPasteboard generalPasteboard];
[generalPasteboard declareTypes:[NSArray arrayWithObjects:MSSectionsPBoardType, NSStringPboardType, nil] owner:self];
NSData *copyData = [NSKeyedArchiver archivedDataWithRootObject:copyObjectsArray];   // Here's where it crashes. ERROR MESSAGE: "-[NSManagedObject encodeWithCoder:] unrecognized selector sent to instance 0x22fd410"

因此,似乎将关系复制到粘贴板的唯一方法必须是归档其URI。在这种情况下,我必须处理引用临时ID的头痛问题。有人可以确认是这种情况吗?它必须这么难吗?

1 个答案:

答案 0 :(得分:1)

您还没有仔细阅读该文档。在自定义员工逻辑部分中,它解释了关系不会被复制,原因有几个。然后解释代码如何处理仅复制特定属性。在选择要复制的特定属性时,您似乎遵循了文档,而不是忽略关系。

至于您所看到的错误,

-[NSManagedObject encodeWithCoder:] unrecognized selector sent to instance 0x22fd410

这是因为您在包含不符合archivedDataWithRootObject:的对象的字典上调用NSCoding,特别是您的托管对象。像这样的存档只能自动用于属性列表类型 - 对于其他所有内容,您必须实现NSCoding,否则会出现此错误。

如果要复制关系,则复制托管对象ID的URI可能是合理的。如果您遇到临时对象ID问题,请执行以下操作之一:

  • 保存更改
  • 调用obtainPermanentIDsForObjects:error:对象以获取永久ID而不保存。