Reputation: 10818
I have a core data model that look something like this:
Author
======
- name
- bio
- books (to-many relationship)
Book
====
- title
- release date
- author (to-one relationship)
I present to the user a table view of authors each table cell represent an author and shows his name
and the title
of the latest book he wrote.
To show the list of authors I use a NSFetchedResultsController
with the following NSFetchRequest
:
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Author"];
request.predicate = nil;
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
request.fetchBatchSize = 20;
My question is:
How should I get the title of the latest book for each author? can I get that info in my original request or do I need to do some additional requests?
Upvotes: 1
Views: 103
Reputation: 8918
You don't need to execute another fetch request if you already have an Author
managed object. Just create a sorted array from the Author
's books
property. To accomplish this, you could use NSSet
's sortedArrayUsingDescriptors:
method and pass in a descriptor that sorts by release date.
Upvotes: 1
Reputation: 8988
To get it as part of the same request you could include an attribute on the Author
object that stores the latest book
Author
======
- name
- bio
- latestBook
- books (to-many relationship)
Then to get the details simply use author.latestBook.title
You would also need to set the latestBook
attribute when you add the latest book to the books
attribute.
Alternately it could be a transient attribute that you calculate from the set of books based on the latest releaseDate
.
Upvotes: 0