Question

Okay so i understand fetch requests, and accessing one to one relationships from one another i can do. I am having a little trouble understanding one to many.

My example: A Suburb has many Streets and these Streets belong to one Suburb. This creates the NSSet property. How do i add a Street and its properties (i.e. @"name") to a particular suburb. I have a TableView listing the Suburbs and when you click on a Suburb it should show the streets associated with that particular Suburb.

I understand there are other Core Data to-many questions on here but reading them it is just not "clicking" over in my head for some reason.

I am using MagicalRecord but from my understanding all that does is minimise the code i have to write and so i need to understand how to do it in Core Data before i can even attempt it on MR.

Was it helpful?

Solution

1: Create an instance of the suburb entity:

    AppDelegate* appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext* context = [appDelegate managedObjectContext];
    Suburb *mySuburb = [NSEntityDescription insertNewObjectForEntityForName:@"Suburb" inManagedObjectContext:context];

2: Initialize the set of streets in the suburb

mySuburb.streets = [[NSMutableSet alloc]init];

3: Create a street:

    Street *myStreet = [NSEntityDescription insertNewObjectForEntityForName:@"Street" inManagedObjectContext:context];

4: "Link" the two

myStreet.suburb = mySuburb;
[mySuburb addStreetObject:myStreet];

Edit: The above is assuming you created the right relationships. Ideally, the streets relationship attribute will be a cascade type relationship and the suburb relationship attribute will be nullify. If that is the case, when you delete a street, it will be gone from the set of streets that belong to a suburb. If you delete a suburb, it will delete all the streets along with it.

Oh and don't forget to save context.

OTHER TIPS

  1. Create query to check whether Suburb is existed. If no, create new Suburb

  2. Get NSSet Streets from Suburb.

    If NSSet *Suburb == nil -> create Street, assign name to this Street -> create new Suburb and assign Street to this Suburb

    If NSSet *Suburb != nil -> insert new Street to Suburb

Hope this idea help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top