Ben Packard
Ben Packard

Reputation: 26516

Max value from core data attribute of different entities

I have three entities in my core data modal, A, B, C. Each has a createdAt date.

What is the quickest way to access the most recent createdAt date, regardless of the entity type? Can I do something like:

(note: fetchobjects... is a just shorthand method to run a execute request)

NSArray *allAs = [context fetchObjectsForEntityName:@"A"];
NSArray *allBs = [context fetchObjectsForEntityName:@"B"];
NSArray *allCs = [context fetchObjectsForEntityName:@"C"];

NSArray *allObjects = [[allAs arrayByAddingObjectsFromArray:allBs] arrayByAddingObjectsFromArray: allCs]

NSDate *latestDate = [allObjects valueForKeyPath:@"@max.createdAt"];

Or is this considered risky (given that I am relying on the name of the attribute being the same in different entities).

Upvotes: 0

Views: 446

Answers (1)

Martin R
Martin R

Reputation: 540065

The first step can be optimized. Instead of fetching all objects of each entity, fetch only the most recent createAt value (per entity):

  • add a sort descriptor to the fetch request that sorts descending by createdAt,
  • set the fetchLimit to 1,
  • set the resultType to NSDictionaryType,
  • set the propertiesToFetch to @[@"createdAt"].

The advantage is that the sorting by date is done on the SQLite level, instead of loading all objects into the managed object context and firing faults to get the createdAt attribute, so this should be faster and less memory intensive.

The allObjects array would then contain only 3 dictionaries (one for each entity).

Upvotes: 1

Related Questions