在我的应用程序中,我有以下CoreData模型:Foo有许多Bar实体:Foo< ---->>杆
为了添加一个新的Foo实体,我创建了一个新的MOC,我在其中创建了一个新的Foo实例。这将显示AddFooViewController。在这里,我可以为此创建的Foo实体取消或保存或添加新的Bar实体。添加新的Bar实体时会出现问题。
让我详细解释一下:新的Bar实体是在一个全新的MOC中创建的。然后,当我决定保存Bar实体时,我尝试合并“Add Bar MOC”和“Add Foo MOC”。这应该通过以下代码完成:
- (IBAction)addNewBar {
BarAddViewController *addViewController = [[BarAddViewController alloc] initWithStyle:UITableViewStyleGrouped];
NSManagedObjectContext *addingContext = [[NSManagedObjectContext alloc] init];
self.addingManagedObjectContext = addingContext;
[addingContext release];
[addingManagedObjectContext setPersistentStoreCoordinator:[self.managedObjectContext persistentStoreCoordinator]];
// Create new bar
Bar *bar = (Bar *)[NSEntityDescription insertNewObjectForEntityForName:@"Bar" inManagedObjectContext:self.addingManagedObjectContext];
bar.creationDate = [NSDate date];
addViewController.delegate = self;
addViewController.bar = bar;
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:addViewController];
[self.navigationController presentModalViewController:navController animated:YES];
[addViewController release];
[navController release];
}
// Delegate method :
- (void)barAddViewController:(BarAddViewController *)controller didFinishWithSave:(BOOL)save {
// Dismiss the modal view to return to the main list
[self dismissModalViewControllerAnimated:YES];
// Save modifications
if (save) {
NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
[dnc addObserver:self
selector:@selector(addBarControllerContextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:addingManagedObjectContext];
// Assign relationship here ???? foo.bars = bar;
NSError *error;
if (![addingManagedObjectContext save:&error]) {
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
exit(-1); // Fail
}
[dnc removeObserver:self
name:NSManagedObjectContextDidSaveNotification
object:addingManagedObjectContext];
} else {
// Remove bar from addingManagedObjectContext
[self.addingManagedObjectContext deleteObject:controller.bar];
NSError *error;
if (![addingManagedObjectContext save:&error]) {
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
exit(-1); // Fail
}
}
// Release the adding managed object context.
self.addingManagedObjectContext = nil;
}
- (void)addBarControllerContextDidSave:(NSNotification*)saveNotification {
[self.managedObjectContext mergeChangesFromContextDidSaveNotification:saveNotification];
}
我的问题是我不知道在哪里建立Foo和Bar之间的关系。我知道我只能在同一个上下文中建立两个NSManagedObject之间的关系。请问有人可以帮助我吗?
提前致谢
答案 0 :(得分:3)
你需要在同一个托管上下文中加载两个实体来创建任何类型的关系(虽然我猜你已经明白了!)。
第一个托管对象上下文中有一个Foo - 称之为Foo1。
Foo *foo1 = {your initial Foo};
// Get a foo from the new managed context
NSManagedObjectID fooID = [foo1 managedObjectID];
Foo *foo2 = [addingManagedObjectContext objectWithID:fooID];
您现在可以使用Foo2创建关系