Search code examples
iosdatabasecore-dataentity-relationshipiphonecoredatarecipes

Adding Data in Entities with the Relationship


enter image description here

In My Model of Core Data , I have such relationship (See Photo)

Now

Location *locObj = [NSEntityDescription insertNewObjectForEntityForName:@"Location"
                                                              inManagedObjectContext [self managedObjectContext]];

Room *roomObj = [NSEntityDescription insertNewObjectForEntityForName:@"Room"    
                                       inManagedObjectContext:[self managedObjectContext]];

I have declare this two entities like this .

Questions :-

  1. As I have declared object of Room and Location , First I need to fill the data of location and then I need to fill the data of Room and then I need to Add room in the location method?Is that correct ?

  2. What If I have the big data ? every time do I need to add objects or is there any custom supported class which we can connect ?


Solution

  • Answer

    1. The order is not important here, but reference to other entity object. You can just use the code

      [locObj addWithRoomObject:roomObj];
      roomObj.withLocation = locObj;
      
    2. There is no such custom supported class. You can just use auto generated accessors in core data and it will automatically handle. You can call the function:

      [locObj addWithRoomObject:roomObj];
      

    UPDATE

    To add more rooms:

    Location *locObj = [NSEntityDescription insertNewObjectForEntityForName:@"Location"
                                                              inManagedObjectContext [self managedObjectContext]];
    
    locObj.locationName = LOCATION_NAME;
    
    Room *room1 = [NSEntityDescription insertNewObjectForEntityForName:@"Room"    
                                       inManagedObjectContext:[self managedObjectContext]];
    // Fill room1 details
    ...
    room1.withLocation = locObj;
    [locObj addWithRoomObject:room1];
    
    Room *room2 = [NSEntityDescription insertNewObjectForEntityForName:@"Room"    
                                       inManagedObjectContext:[self managedObjectContext]];
    // Fill room2 details
    ...
    room2.withLocation = locObj;
    [locObj addWithRoomObject:room2];
    
    // so on..