CoreData:如何通过其主键对NSManagedObject进行排序? [英] CoreData: How to sort NSManagedObject by its primary key?

查看:227
本文介绍了CoreData:如何通过其主键对NSManagedObject进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSManagedObject的子类,如下面的
和存储一些实例由NSManagedObjectContext。

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


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

现在,我想获取按其主键排序的列表(自动创建)。
我试过NSFetchRequest并得到运行时错误:实体中找不到keypath id。

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类添加一些列进行排序吗?

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

推荐答案

假设主键是一个不透明的数据类型,一个任意的实现细节完全在你的控制之外(包括随着时间的推移可能不是恒定的),它似乎没有意义的想要排序。

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.

请注意,一般而言,如果您要使用一个新的属性,最好不要在关系数据库术语中考虑核心数据。关注对象图和对象建模方面,因为这是API的重点。

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.

这篇关于CoreData:如何通过其主键对NSManagedObject进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆