Good evening Sirs,
I am having a little trouble performing a 'query' using NSPredicate on two entities in my Core Data project.
The two entities are:
Author {authorName, dateOfBirth}
Book {authorName, bookName, pages}
I have setup the relationships correctly (one author has many books, inverse).
At the moment I can click on an author in a view controller, and it will take me to a detail view controller that will display all books by all authors. I would much rather the detail view controller displayed all the books by a certain author (the one that is clicked in the view controller).
I presume I need to do a NSPredicate Query to achieve this? So far I have:
Code:
// Gets new name of author.
NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
NSString *newAuthorName = [[selectedObject valueForKey:@"authorName"] description];
// Begin predicate query.
NSFetchRequest *myFetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Books" inManagedObjectContext:managedObjectContext_];
[myFetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@==%@", newAuthorName, authorName];
[myFetchRequest setPredicate:predicate];
NSError *error;
NSArray *listArray;
listArray = [[managedObjectContext_ executeFetchRequest:myFetchRequest error:&error] mutableCopy];
NSLog(@"listArray: %@", listArray);
I would expect that this would return all the books by a certain author (the relevant author name is passed into the detail view controller from the prior view controller).
However, I am not sure I am using the correct code for the predicate as they are my weakness.
Also, I am a little unsure what to do with the returned 'listArray'.
I would be very grateful if anyone could help me out here. I think I have explained the problem pretty well, but if more clarity is needed just ask