【问题标题】:Sort data in array对数组中的数据进行排序
【发布时间】:2014-03-28 23:44:55
【问题描述】:

我有一个来自 Core Data 的数组,我想使用我添加到数据库中的 orderNum 字段(Scene 实体)进行排序。

我提出以下请求以获取数据:

NSArray *scenes;

NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Scenes" inManagedObjectContext:context];

[fetchRequest setEntity:entity];
NSError *error;

scenes = [context executeFetchRequest:fetchRequest error:&error];
return scenes;

如何将scenes 返回的数据按orderNum 排序?

【问题讨论】:

  • 为什么在调用数据库时不排序?
  • 这是我正在维护的预构建应用程序。我无法弄清楚在数据库中调用此表的查询的位置。就像我会修改 SQL 以按 orderNum 排序一样。任何想法,我如何在程序中跟踪它?
  • @user3473089 如果您现在正在维护此代码,那么阅读Core Data Programming Guide 似乎是当务之急。

标签: ios objective-c sorting core-data


【解决方案1】:

使用NSSortDescriptororderNum 作为key,并将该排序描述符应用于您的fetchRequest

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"orderNum" ascending:YES];
[fetchRequest setSortDescriptors:@[ sort ]];

【讨论】:

  • 是的,这是正确的方法 - 值得注意的是,让 SQL 引擎在提取过程中进行排序将比检索数据然后在代码中对其进行排序更快、更有效。特别是如果您在 SQL 领域中对具有索引的列进行排序...
  • 你知道我如何访问 SQL 引擎吗?
  • 您无法通过 Core Data 直接访问 SQL。调用executeFetchRequest: 将获取请求转换为 SQL 并运行它(私下)。
【解决方案2】:

最好的方法是从排序后的数据库中检索数据。检查@Wain 答案。

但是,也可以将数据分类到 NSArray 的字典中:

NSSortDescriptor *sceneDescriptor = [[NSSortDescriptor alloc] initWithKey:@"orderNum" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject: sceneDescriptor];
NSArray *sortedArray = [scene sortedArrayUsingDescriptors:sortDescriptors];

NSLog(@"sortedArray = %@", sortedArray);

【讨论】:

    猜你喜欢
    • 2013-09-10
    • 2012-12-01
    • 2011-07-27
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 2017-12-10
    • 2015-11-03
    相关资源
    最近更新 更多