Scott 提到的博客对于使用 MagicalRecord 的人来说是必读的。
此外,如果默认值+ (id) importFromObject:(id)data
不适用于您的某些 NSDictionary 数据,您始终可以覆盖- (BOOL) importValuesForKeysWithObject:(id)objectData
NSManagedObject 子类中的方法以实现对映射的精确控制。
这是我最近的一个项目的一个片段:
// override MagicalRecord's implementation with additional set up for Dialogue relationship
- (BOOL) importValuesForKeysWithObject:(id)objectData {
BOOL result = [super importValuesForKeysWithObject:objectData];
// update lesson-dialogue data
id dialogueDicts = [objectData objectForKey:@"dialogue"];
if ([dialogueDicts isKindOfClass:[NSArray class]]) {
for (id dialogueDict in dialogueDicts) {
DialogueSentence *dialogue = [DialogueSentence findFirstByAttribute:@"id" withValue:[[dialogueDict objectForKey:@"id"]];
if (dialogue == nil) {
dialogue = [DialogueSentence createEntity];
}
[dialogue importValuesForKeysWithObject:dialogueDict];
[self addDialoguesObject:dialogue]; // connect the relationship
}
}
return result;
}
顺便说一句,您可能想要创建 NSManagedObject 子类的类别并在那里编写覆盖代码,因为当您升级 Core Data 模型版本并重新生成 NSManagedObject 子类时,您自己的代码不会被清除。