Core Data relationships (swift)
Asked Answered
S

1

6

I'm building an app that requires a core data relationship as such:

entityA <<---> entityB  (e.g. any given entityA can hold many entityB objects)

I have two tableviews with entityA list items in which I want to be able to store entityB objects in any given entityA object.

I'm new to using relationships with core data (and fairly new to swift) and would like to learn how to make this work. Does anyone have any swift tutorials in mind that would be good for me to take a look at or any other resources that may help me learn?

Sorry if my question doesn't make much sense, ask me to clarify if you need.

Thanks!

UPDATE:

Here's a bit more specificity on what I'm wanting to learn.

Lets say I have the entity "Person" (attributes may include name, age, etc.) and a tableview in which my app users can add a person to. (this I have established and know how to do appropriately) But, now I want to add the entity "Meal" (attributes may include food items), and Meal is a tableview of its own that I can access by choosing the person that I want to add a meal to. Each person can have more than one meal, but there can only be one person per meal.

The question is: what would my core data model, fetchRequests, etc look like in order to accomplish this?

Hope that is clear enough! :)

Thanks

enter image description here

Here's a code snippet of my function for creating a meal:

    func createMeal() {
    let entityDescription = NSEntityDescription.entityForName("Meal", inManagedObjectContext: managedObjectContext!)
    let meal = Meal(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)

    meal.mealName = mealNameTxt.text
    meal.mealItem1 = mealItem1Txt.text

    managedObjectContext?.save(nil)
}
Stomatitis answered 4/2, 2015 at 16:52 Comment(2)
See Core Data By Tutorials from raywanderlich.com ... Ch 3 and 4 discuss node editor & structuring "to-many" relationships, plus different options for fetching filtered subsets of data. ... Where in the code snippet above do you connect the new meal to a specific person? You're just creating it & adding it to the context w/o associating it w/any person entity. BTW your "A & B" arrows above are pointing the wrong way for what you describe. Your "Person & Meal" screenshot looks correct (many meals), but the attribute names don't match your code snippet.Fruma
Check out my Core Data Relationship Demo: github.com/iMac239/CoreDataRelationshipDemo hope it helps!Gravestone
P
4

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

enter image description here

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

enter image description here

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

enter image description here

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

enter image description here

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)
Primordial answered 4/2, 2015 at 17:14 Comment(10)
thanks for the reply @Ashraf Tawfeeq, I believe that I have my app set up how you just described, but right now when I add a meal to person (as in my update example above) it adds it appropriately, but when a add a meal to personA and navigate to personB to look at their list of meals (a separate tableview from the person tableview) I find that personA and personB share the same meal that I just added. How do I get each meal to be specific to the person that I have selected? ThanksStomatitis
Can you show me how you're adding a meal to a person?Primordial
just added a screenshot of the example model. is that what you're wanting?Stomatitis
just added my function for create meal. I have no idea how to add a meal to a specific person, thats my question. Because I thing right now createMeal function creates a meal for every person. correct?Stomatitis
I have just edited the answer with a code snippet. Sadly, it's written in Objective-CPrimordial
I don't know if I completely understand objective-c, but wouldn't this case only allow one tableview? In my case I have a tableview for people, and another tableview (for meals) that is shown via segue from person detail view.Stomatitis
If we replaced the branch with the person and the specs with the meal. I am adding a set of meals to a man. And when fetching a specific man, Core Data automatically fetches the meals assigned to him and set man's property meals.Primordial
ok, sounds like what I need. Is there any chance you could help me out with what that'd look like in Swift?Stomatitis
Okay, I'm still trying to figure this out. Sorry I'm slow (been trying out iOS development for a few months now). I have a NewPersonViewController that takes data from text fields (for person age, name) and then fills out a PersonTableViewController by use of FetchedResultsController. Where Meals comes in to this is where I have a button in NewPersonViewController to segue to MealsTableViewController and an add button segue to NewMealViewController where I can add foodItem1 etc. Question is: in what class would I put the above code? NewPersonViewController? or NewMealViewController?Stomatitis
@AshrafTawfeeq well it is not adding against a specific value, it s adding for all values , what will be the solution???Chinch

© 2022 - 2024 — McMap. All rights reserved.