I’m missing the boat on something that I thought I had the hang of and was hoping someone here could help.
I’m using Xcode version 4.4 and my project is using Core Data, Storyboards and ARC.
My project has the following 3 entities.
All works well with the Livestock and Notes entities. But when I try to save data to the Taxonomy entity nothing happens. I get no error but the data is not saved.
Is it ok that I not use an array for the fetched results? Based on my predicate, I’m expecting only one object to be returned so I thought I didn’t need an array. Below is my code that does the saving. I have verified that data is being passed in from the view's text variables.
AppDelegate *appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.entity = [NSEntityDescription entityForName:@"Livestock" inManagedObjectContext:managedObjectContext];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"tank == %@ AND type == %@ AND name == %@", self.detailTank, self.detailType, self.detailName];
NSError *error = nil;
Livestock *livestock = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] lastObject];
if (error) {
NSLog(@"TaxonViewController: saveTaxonomy: Retrieving Livestock Record for saving: error = %@", error);
}
Taxonomy *taxonomy = livestock.taxonChildren;
taxonomy.kingdom = self.kingdom.text;
taxonomy.phylum = self.phylum.text;
taxonomy.classs = self.classs.text;
taxonomy.order = self.order.text;
taxonomy.family = self.family.text;
taxonomy.genus = self.genus.text;
taxonomy.species = self.species.text;
taxonomy.common = self.common.text;
taxonomy.livestockParent = livestock;
error = nil;
if (![managedObjectContext save:&error]) {
NSLog(@"Taxonomy save error. error = %@, userInfo = %@", error, [error userInfo]);
}
Any insight is greatly appreciated! Thanks!
UPDATE 1:
Modified code to test for NULL taxonChildren value. This solved it for me. Thanks Jesse!
if (livestock.taxonChildren == NULL) {
Taxonomy *taxonomy = [NSEntityDescription insertNewObjectForEntityForName:@"Taxonomy" inManagedObjectContext:managedObjectContext];
taxonomy.kingdom = self.kingdom.text;
taxonomy.phylum = self.phylum.text;
taxonomy.classs = self.classs.text;
taxonomy.order = self.order.text;
taxonomy.family = self.family.text;
taxonomy.genus = self.genus.text;
taxonomy.species = self.species.text;
taxonomy.common = self.common.text;
taxonomy.livestockParent = livestock;
}
else {
Taxonomy *taxonomy = livestock.taxonChildren;
taxonomy.kingdom = self.kingdom.text;
taxonomy.phylum = self.phylum.text;
taxonomy.classs = self.classs.text;
taxonomy.order = self.order.text;
taxonomy.family = self.family.text;
taxonomy.genus = self.genus.text;
taxonomy.species = self.species.text;
taxonomy.common = self.common.text;
taxonomy.livestockParent = livestock;
}