Could you please help me with the following
I writing an app using CoreData and have two view controllers.
ControllerA is a table view and just lists the data
ControllerB is a view controller containing several UITextFields
To edit a row on ControllerA I set a property on ControllerB passing my CoreData entity model object
eg.
viewControllerB.item = [self.fetchedResultsController objectAtIndexPath:indexPath];
Once this is edited, the contents of item on ViewControllerB is passed back to ViewControllerA via delegate and saved.
This works fine, The bit i’m struggling with is the best way of adding a new item to CoreData without setting up the managedObjectContext on ViewControllerB.
I have tried passing a new object with
ItemData *item = [NSEntityDescription insertNewObjectForEntityForName:@"ItemData" inManagedObjectContext:self.managedObjectContext];
viewControllerB.item = item;
this works if I enter the form on ViewControllerB with data, but if I cancel the view and pop it off i’m left with a (null) object in CoreData.
I also tried instantiating the CoreData ItemData object using a standard init, but now understand this won’t work because CoreData doesn’t understand the context and also doesn’t have getter/setters for the properties.
What is best practice for this situation?
1) Should I just pass managedObjectContext to viewControllerB?
2) Create a model class to hold the values from the form and pass that back and then deal with CoreData stuff?
3) or is there a correct way of doing what i’m trying to do?
I’m loosely following iOS Apprentice 2 to deal with Storyboards etc, but in this a model class is passed back and forth which I know works fine, its the CoreData side thats the problem.
I hope the above is clear and that the terminology i’ve used is correct.
Look forward to any help.
If you close the view you need to delete the object if you don’t want it to stay. So if someone hit’s “abort” in on your view you should call
There are many possible ways of passing the managed object context between controllers. Your AppDelegate should have the managed object context as a property.
If controller a has a pointer to the context you could just pass this into an
(nonatomic, weak)property of controller B.