1
我创建了一个核心数据模型,它有三个实体,称为Customer,Form1和Form2。我已经建立了从客户到form1和form2的反向关系,反之亦然。所以当创建一个新客户时,需要为该客户创建form1和form2。我遇到的问题是在客户被删除后,为每个客户访问正确的form1或form2。那么,我如何正确地添加和删除所有三个实体中的对象。让我知道如果我以正确的方式做所有事情,因为我以前从来没有在多个实体中工作过,并且在可用视图中工作过。任何帮助将是伟大的!核心数据与多个实体和uitableview
-(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];
}
}
所以你说我应该加入和访问form1和form2做这样的事情:textFieldQ1.text = customer.form1.question1。我要试试这个。我会让你知道它是如何工作的。 – Sean
是的..它会像你访问你自己的数据对象一样容易.. – vishy
我现在无法保存它。在viewWillDisappear我这样做\t NSManagedObjectContext * context = customer.form1.managedObjectContext; \t error = nil; \t [context save:&error];但它什么都不做。所以我想出了customer.form1.managedObjectContext = null,但是customer.managedObjectContext不为null。我如何通过是为了节省customer.form1 – Sean