I have a pretty simple base of an app so far, two textfields where the user enters the first and last name of a person and then when they tap the save button the following code runs:
person = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext];
NSError *err;
if (![managedObjectContext save:&err])
{
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", err, [err userInfo]);
exit(-1); // Fail
}
So I have a Person
object, I set the first and last name as the user types into the textfield and then insert the object when choosing save. However, after saving, the first and last name are showing as (null)
. I have all my outlets and methods hooked up correctly all code is being ran to set and save the name/object.
However, if I do this in the master view:
Person *p = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext];
PersonDetailViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"PersonDetail"];
vc.managedObjectContext = fetchedResultsController.managedObjectContext;
vc.person = p;
And then save my object, the values are not (null)
. I am trying to insert the new object after deciding to save, rather than creating it then deleting it if cancelling to have cleaner and more logical code.
Turns out my Person
object was returning nil.
Solution:
Initialise a Person
object with nil context so that it isn't inserted but not nil. This way I can make sure of its variables to store things such as first and last name, then insert is like below.
person = [[Person alloc] initWithEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:managedObjectContext] insertIntoManagedObjectContext:nil];
Person *p = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext];
p.firstName = person.firstName;
p.lastName = person.lastName;
This helped me reach this: Is there a way to instantiate a NSManagedObject without inserting it?