我有一个 NSManagedObject 的子类,如下所示 并通过 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];
是否可以按主键排序?还是应该在 Model 类中添加一些列进行排序?
最佳答案
鉴于主键是一种不透明的数据类型,其值是完全不受您控制的任意实现细节(包括可能不会随时间变化),因此想要按它排序似乎没有意义。
如果您正在寻找稳定、确定的顺序,那么——是的——按不同的属性排序,可以是现有属性,也可以是新属性。
请注意,一般来说,最好不要从关系数据库的角度考虑 Core Data。关注对象图和对象建模方面,因为这是 API 所关注的。
关于iphone - 核心数据 : How to sort NSManagedObject by its primary key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3120136/