I’d like to implement a dynamic property on a Core Data model but am unclear as to whether this is supported, and if so… how?
The idea is to have a model with a set number of non-dynamic fields, such as created_at, updated_at, start_at, end_at, etc. These would be dates. I’d then like to include a dynamic property called “is_archive” which would perform a basic check against the “end_at” property and return True or False.
I know that I can update the Model to add a custom property, but am unclear as to how I could implement this so that I can include “is_archive” in an NSSortDescriptor.
Right now, I have:
NSFetchRequest *request = [[NSFetchRequest init] alloc];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"event" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSSortDescriptor *sort1 = [[NSSortDescriptor alloc] initWithKey:@"start_at" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObjects:sort1,nil]];
What I’d like to do is add:
NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] initWithKey:@"is_archive" ascending:NO];
In SQL, I would normally do this with a CASE statement, such as:
select *
from event e
order by case when e.end_at > curdate() then 1 else 0 end desc, e.end_at asc;
So I suppose the question is:
How can I do a “CASE WHEN x > y THEN true ELSE false END” with a Core Data NSSortDescriptor, or the equivalent.
David,
It is difficult, if not impossible, to make a fetch request using dynamic properties. In Core Data, one typically over fetches an entity and then refines the resultant array using predicates, such as with -filteredArrayUsingPredicate:. While at first glance this appears to be wasteful, it is relatively memory efficient and fast.
Andrew