JSON to Core Data with Relationships

后端 未结 2 1996
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 21:06

Following Ray Wenderlich\'s new tutorial I was able to get JSON data and store it into Core data. I am having a really hard time understanding how to do this with relationships

相关标签:
2条回答
  • 2021-02-04 21:56

    In your for loop you are going to do some special handeling, if you're dealing with a QuestionGroup you will know that an array on that object is questions (assuming it is the only array) so you can create a new Question object for each entry in the dictionary. This is going to break the genericness of the sync engine but you could go through some extra steps to regain it if desired.

    else if ([value isKindOfClass:[NSArray class]]) {
        if ([[managedObject entity] name] isEqualToString:@"QuestionGroup") {
            NSSet *questions = [NSMutableSet set];
            for (NSDictionary *question in value) {
                // create your question object/record
                NSManagedObject *questionManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Question" inManagedObjectContext:managedObjectContext];
                // setup your question object
                questionManagedObject.text = [question valueForKey:@"text"];
                // store all the created question objects in a set
                [questions addObject:questionManagedObject];
            }
            // assign the set of questions to the relationship on QuestionGroup
            [managedObject setValue:questions forKey:@"questions"];
        }
    }
    
    0 讨论(0)
  • 2021-02-04 22:04

    I have used restkit in the past to handle this. I felt it was pretty heavy for what I was doing, but now that I'm working on another project that needs to solve the same problem, I'm not finding anything that will work better. I Guess its time to dust off restkit once again.

    Have a look at http://restkit.org

    0 讨论(0)
提交回复
热议问题