views:

41

answers:

1

I have one subclass of NSManagedObject like following and stored some instances by NSManagedObjectContext.

@interface SomeModelObject : NSManagedObject  
  @property (nonatomic, retain) NSString * text; 
@end

Now, I want to fetch the list sorted by its primary key (created automatically). I've tried NSFetchRequest and got runtime error: "keypath id not found in entity".

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"SomeModelObject" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sort, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

Is it possible to sort by primary key? Or should I add some column to Model class for sorting?

+2  A: 

Given that the primary key is an opaque data type whose value is an arbitrary implementation detail completely outside of your control (including potentially not being constant over time), it seems non-sensical to want to sort by it.

If you are looking for a stable, determined, order, then -- yes -- sort by a different attribute, either an existing one or a new one.

Note that, in general, it is best to not think of Core Data in relational database terms. Focus on the object graph and object modeling aspects as that is what the APIs are focused upon.

bbum
Thank you very much!I will add some column for sorting.Yes, I understand Core Data treat object graph not RDB.But I think some ways may exist to fetch data without any NSSortDescriptor. I just want to fetch in the inserted order.Its little annoying that all model objects must have sorting column, don't you think so?
taichino
In a pure RDB, you'd have to do the same (example: sqlite has rowids, but they change when the database is vacuumed)... Regardless, the notion of an "insertion order" is something that is quite specific to your particular business case and, thus, is not something that should be provided "for free" given that most entities have no need.
bbum
Umm... you're right, its my specific case. I've been working with database in years, so I'm feeling awkwardness for using CoreData for now... Anyway I'll keep trying, thanks again!
taichino