I have one-to-many parent-child entity Book <->> Borrow
Book
- name
- borrows (relation)
Borrow
- borrowDate
- note
- book (relation)
and I want to sort Book entity in NSFetchedResultsController using max NSDate of child entity to show most recently borrowed book.
How can I do this ? I tried using my own method something like this using Category on Book
- (NSArray *)borrowSortedByborrowedDate
{
NSSortDescriptor *sortByCreatedDate = [NSSortDescriptor sortDescriptorWithKey:@"borrowDate" ascending:NO];
NSArray *sortedArray = [self.histories sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortByCreatedDate]];
return sortedArray;
}
- (NSDate *)recentBorrowDate
{
Borrow *borrow = [[self borrowSortedByborrowedDate] objectAtIndex:0];
return borrow.borrowDate;
}
and put it in sortDescriptor
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"recentBorrowDate" ascending:YES];
but it didn’t work.
Here is my fetched request (Didn’t work)
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"recentBorrowDate" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
My expected result is
- Book name1 (borrowDate today)
- Book name2 (borrowDate yesterday)
- Book name3 (borrowDate many days ago)
I have the same issue and this is my current workaround to achieve the desired output. (maybe this is the only way, but I am still looking…)
When creating a new Borrow just update the book.lastBorrowDate property at the same time.
Now when pulling them out later it’s easy…