【问题标题】:Sort Core Data request ascending对核心数据请求进行升序排序
【发布时间】:2015-05-06 14:17:40
【问题描述】:

我正在尝试使用字符串类型的“groupID”对我的获取请求进行升序排序,但其中保存了一个数字,在计数器的形式下,问题是返回的数组不是“正确”排序的,不是我想要的那样,因为它返回的元素排序为:0、1、10、2、3、4、5、6、7、8、9,而不是预期的 0、1、2、3 ... 9、10

我设法找到了两个解决方案: 1 - 将核心数据属性从字符串修改为 int(最不需要的场景) 或者 2 - 从核心数据中获取所有元素,在数组中检索所有元素,使用数组的大小运行 for 循环,并在 for 循环内部使用 for 循环计数器使用谓词进行另一个提取,并且返回的实体我可以保存在一个数组中,所以通过执行所有这些操作,我将得到一个包含实体的排序数组

这是我当前的代码:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"SuggestedChannelsEntity" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

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

NSError *error = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

【问题讨论】:

    标签: objective-c xcode core-data nsfetchrequest


    【解决方案1】:

    您可以使用其中一种排序选择器“localizedStandardCompare:”,如下所示:

    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"groupID" ascending:YES selector:@selector(localizedStandardCompare:)];
    

    如果数字不是负数,这似乎可以正常工作。

    【讨论】:

    • 感谢您的回答,能否提供一些文档的链接?那将不胜感激:)
    • @LaurStefan 请参阅排序描述符文档here,特别是标题为“指定自定义比较”的部分,以及关于持久存储功能here 的核心数据编程指南部分,特别是关于“FetchPredicates”的部分和排序描述符”。
    猜你喜欢
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    相关资源
    最近更新 更多