Ramaraj T
Ramaraj T

Reputation: 5230

Core Data multiple objects for single entity

I am new to the Core Data. I am trying to create an employee database using Core Data. I store the user name and his birthday in an entity Employee and the employee can have multiple phone numbers. So I have created another entity PhoneNumbers to store the phone number. I have made the relationship for the two entities. But when I try to insert two phone number for the employee, only the second phone number have the relationship to the employee.

I don't know how to alter my core data model.

enter image description here

This is how I insert the data's to the Core Data.

  NSManagedObject *entry = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_managedObjectContext];
[entry setValue:@"Suresh" forKey:@"name"];
[entry setValue:[NSDate date] forKey:@"birthdate"];

NSManagedObject *phoneEntry = [NSEntityDescription insertNewObjectForEntityForName:@"PhoneNumbers" inManagedObjectContext:_managedObjectContext];
[phoneEntry setValue:@"9600492944" forKey:@"phone"];

[phoneEntry setValue:entry forKey:@"owner"];
[entry setValue:phoneEntry forKey:@"phone"];

NSError *error = nil;
if (![_managedObjectContext save:&error]) {
    NSLog(@"hi %@", [error localizedDescription]);
}

NSManagedObject *phoneEntry1 = [NSEntityDescription insertNewObjectForEntityForName:@"PhoneNumbers" inManagedObjectContext:_managedObjectContext];
[phoneEntry1 setValue:@"1234567890" forKey:@"phone"];

[phoneEntry1 setValue:entry forKey:@"owner"];
[entry setValue:phoneEntry1 forKey:@"phone"];

if (![_managedObjectContext save:&error]) {
    NSLog(@"hi %@", [error localizedDescription]);
}

Upvotes: 1

Views: 1041

Answers (3)

RAJA
RAJA

Reputation: 1214

In your coredata model, select the relationship phone in employee entity and change the type of it to "To Many"... it will create the relation between Employee and PhoneNumbers as one-to-many relationship.

After changing the above, you can store multiple phone numbers for an employee...

Upvotes: 1

sanjaymathad
sanjaymathad

Reputation: 232

That is because you have not set relationship properly. As you can see in the screenshot that you have attached, it shows single arrow pointing to phone number (like this >) instead of 2 arrows (like this >>). So click the Employee entity, click the phone relationship. You can see the toolbar on the right, click the relationship button (third one) set the Type as to Many. It will solve your problem. Also if you want that the phone number entity related to the person automatically gets deleted, then set the Delete Rule to Cascade. Hope it helps.

Upvotes: 2

Volker
Volker

Reputation: 4658

Your relationship has to be a one to multiple - from your screenshot I see you have a one-to-one relationship. Redefine the relationship and it should work.

Upvotes: 1

Related Questions