0

That is, I have an entity A with a to-many relationship with entity B. B instances have, among other attributes, a creationDate. And I also already have a managed object for A in memory.

So I know I can access all B instances through A's accessor. But I'd like to do something along the lines of:

"for all Bs in A.relationshipName, return the managed object for the B with the most recent B.creationData"

How could I go about it?

2 Answers 2

1

How about performing another fetch request:

Assuming the relationship name on the one of the one-to-many side is a

// 1
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity  = [NSEntityDescription entityForName:@"B"
                                           inManagedObjectContext:self.managedObjectContext];
fetchRequest.entity = entity;

// 2
fetchRequest.fetchLimit = 1;

// 3
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"self.a = %@", previouslyFetchedAObject];

// 4
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate"
                                                               ascending:NO];

NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
fetchRequest.sortDescriptors = sortDescriptors;

In plain English

  1. Make a new fetch request for B
  2. Set the fetch limit so you only return 1 object
  3. Set a predicate that only pulls back objects that have a relationship to the already fetched A object
  4. Set the order descending on date so you get newest dates first
0

Alternately, since you already have a managed object A in memory, you could do an in-memory filtered sort of the A->>B relationship.

A *inMemoryA = ...

id byDate = [NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES];
id sorters = [NSArray arrayWithObjects:byDate, nil];
NSArray *sortedBs = [inMemoryA allBs] sortedArrayUsingDescriptors:sorters];

B *mostRecentB = [sortedBs lastObject];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.