排序核心数据请求升序

Sort Core Data request ascending

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

我设法找到了两个解决方案: 1 - 将核心数据属性从 string 修改为 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];

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

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

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