Aram Boyajyan
Aram Boyajyan

Reputation: 844

Use NSFetchRequest to get all results of relationship

I have two entities: Author and Book. I want to get the list of all books by a particular author.

Here's the code I'm using:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Books"];
[fetchRequest setPredicate[NSPredicate predicateWithFormat:@"ANY author == %@", author]];
books = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

However, this returns only one book of the author.

How can I get ALL books of a particular author?

I read a bunch of other topics but none of the solutions seem to work for me.

Thanks!

Upvotes: 0

Views: 360

Answers (2)

Aram Boyajyan
Aram Boyajyan

Reputation: 844

The issue was in the data model: relationship author -> book should be "To many" instead of "To one".

After updating the relationship I had to reinstall the app in the simulator, but everything worked properly after that.

Upvotes: 1

Kujey
Kujey

Reputation: 1122

Did you try like this ?

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Books"];
request.predicate = [NSPredicate predicateWithFormat:@"author = %@", author ];
NSArray *matches = [moc executeFetchRequest:request error:nil];

Upvotes: 2

Related Questions