Reputation: 26516
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
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):
createdAt
,fetchLimit
to 1, resultType
to NSDictionaryType
,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