Reputation: 345
I created a core data model that has three entities called Customer, Form1 and Form2. I've set up inverse relationships from Customer to form1 and form2 and vise versa. So when a new customer is created form1 and form2 need to be created for that customer. The problem that I am having is accessing the correct form1 or form2 for each customer after a customer has been perviously deleted. So how do i properly add and delete the object from all three entities. Let me know If I am doing everything in the correct way because I've never worked with multiple entities before and in an uitableview. Any help would be great!
-(void) viewDidLoad
{
// Generate a fetch request for reading from the database and set its entity property
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName: @"Customer" inManagedObjectContext: managedObjectContext];
request.entity = entity;
[entity release];
// Perform the actual fetch from the permanent store and initialize the menuItems array with the results
NSError *error = nil;
customerArray = [[managedObjectContext executeFetchRequest: request error: &error]
[request release];
}
- (void) addItem
{
// Insert a new record in the database
Customer * customerItem = [NSEntityDescription insertNewObjectForEntityForName: @"Customer" inManagedObjectContext: managedObjectContext];
NSError *error = nil;
// Insert a new item in the table's data source
[customerArray insertObject: customerItem atIndex: 0];
[NSEntityDescription insertNewObjectForEntityForName: @"Form1" inManagedObjectContext: managedObjectContext];
[NSEntityDescription insertNewObjectForEntityForName: @"Form2" inManagedObjectContext: managedObjectContext];
[managedObjectContext save: &error];
// Insert a new row in the table
NSIndexPath *indexPath = [NSIndexPath indexPathForRow: 0 inSection: 0];
[table insertRowsAtIndexPaths: [NSArray arrayWithObject: indexPath] withRowAnimation: UITableViewRowAnimationFade];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// Delete item from the context and save the context. This removes the item from the permanent store.
[managedObjectContext deleteObject: [customerArray objectAtIndex: indexPath.row]];
NSError *error = nil;
[managedObjectContext save: &error];
// Remove the item from the table's data source array
[customerArray removeObjectAtIndex: indexPath.row];
// Delete the item from the table itself.
[tableView deleteRowsAtIndexPaths: [NSArray arrayWithObject: indexPath] withRowAnimation: YES];
}
}
Upvotes: 1
Views: 1229
Reputation: 3231
As you have made relationship from customer to form1 & form2. You can access the form1 & form2 from customer.
Raywinderlich has a nice tutorial for demonstrating core data with relation ship, implement in the same way.
Upvotes: 1