Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData: How to sort NSManagedObject by its primary key?

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?

like image 670
taichino Avatar asked Jun 25 '10 17:06

taichino


1 Answers

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.

like image 106
bbum Avatar answered Sep 29 '22 17:09

bbum