In my app, I have my master view controller which displays all my coredata objects.
When the user adds an object this runs and the next detail view opens to enter details for the new object:
-(IBAction)addPerson:(id)sender
{
Person *p = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext];
PersonDetailViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"PersonDetail"];
vc.managedObjectContext = fetchedResultsController.managedObjectContext;
vc.person = p;
vc.isNewPerson = YES;
[self.navigationController pushViewController:vc animated:YES];
}
Now I have a delete button in the detail view which calls this:
[managedObjectContext deleteObject:person];
NSError *err;
if (![managedObjectContext save:&err])
{
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", err, [err userInfo]);
exit(-1); // Fail
}
This is how I currently cancel a new coredata object. However I am having issues with it.
How would you recommend I best cancel the creation of a new object? Create and delete, or never create it until confirmed? I’m unsure.
I’d actually never create the managed object until confirmed!
But in the first place I’d rewrite the
PersonDetailViewControllerto not have a dependency to thePersonentity at all (loose coupling). Instead I’d define properties in yourPersonDetailViewControllerfor the various attributes of thePersonobject you like to set/edit and then handle the creation of thePersonmanaged object in a save delegate method or so. With this approach you could also cancel the creation use-case half through, without the need for creation of a new managed object etc.For better illustration, the delegate method would look somewhat like this: