Core Data relationships (swift)

北城余情 提交于 2019-12-03 08:45:20

Well, it's pretty simple. Let's have an example, you have a branch and the branch has lots of specifications. Firstly you need to go to your xcdatamodel and create your data entities

Then you open you editor (table style) and make the relation in your branch entity

After that you will need to set up the relation typo in your branchSpecs too

And that's it! You have just created a relationship between your CoreData entities. All you need to do is to generated the subclassed objects

And now you're all set. You will find a NSSet * object in your branch class that holds the data related specs of that branch. Also your will find a method called addSpecsObject that you can use to store the specs object.

A code sample in my case:

Branch * branch = [NSEntityDescription insertNewObjectForEntityForName:@"Branch"
                                                  inManagedObjectContext:managedObjectContext];
    branch.name = obj.name;
    branch.lattitude = obj.latitude;
    branch.longitude = obj.longitude;
    branch.dispalyedDescription = obj.dispalyedDescription;


    for (FLBranchesSpecs * spec in obj.branchSpecs) {
        BranchSpecs * branchSpec = [NSEntityDescription insertNewObjectForEntityForName:@"BranchSpecs"
                                                        inManagedObjectContext:managedObjectContext];
        branchSpec.type = @(spec.type);
        branchSpec.key = spec.key;
        branchSpec.value = spec.value;
        [branch addSpecsObject:branchSpec];
    }

    NSError *error;
    if (![managedObjectContext save:&error])
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);

A something similar than what you want

let person: AnyObject = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: self.managedObjectContext!)
    //do you code assignment here
    for meal in listOfMeals{
        person.addMealObject(meal)
    }
    var error: NSError?
    self.managedObjectContext?.save(&error)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!