MagicalRecord importFromObject: JSON with dictionary?

后端 未结 2 2025
南方客
南方客 2021-01-07 03:14

I\'m parsing some JSON which comes to me in this format:

{
dataId = \"823o7tr23d387g\";
category = \"link\";
details = {
    text = \"Some text associated wi         


        
2条回答
  •  不思量自难忘°
    2021-01-07 04:16

    The blog Scott mentioned is a must read for who use MagicalRecord.

    In addition, if the default + (id) importFromObject:(id)data doesn't work on some of your NSDictionary data, you can always override the - (BOOL) importValuesForKeysWithObject:(id)objectData method in your NSManagedObject subclass to achieve the exact control over mapping.

    Here's a snippet from one of my recent project:

    // 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;
    }
    

    By the way, you may want to create a category of your NSManagedObject subclass and write the overriding code there, because when you upgrade your Core Data model version and re-generate the NSManagedObject subclasses, your own code won't be wiped out.

提交回复
热议问题