开发者

Core Data, Dynamic Properties or CASE Sort?

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 开发者_如何学Pythoncan 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


use NSPredicate

check out this link http://cocoawithlove.com/2008/03/core-data-one-line-fetch.html

---edit

I can't tell you how to do this in clear and good code. But you can create two arrays using predicate - one with array of is_archived set to YES and the other set to NO, apply sort descriptors to both and concatenate them. I know that's pretty dirty...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜