Objective c 在NSSortDescriptor中使用KVC

Objective c 在NSSortDescriptor中使用KVC,objective-c,core-data,nsfetchrequest,nssortdescriptor,key-value-coding,Objective C,Core Data,Nsfetchrequest,Nssortdescriptor,Key Value Coding,我需要根据存储在NSString中的整数对一组对象进行排序 我知道这是一个解决方案,它是有效的: NSSortDescriptor *mySortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"from" ascending: YES comparator:^(id obj1, id obj2) { if ([obj1 integerValue] > [obj2 integerValue]) { re

我需要根据存储在
NSString
中的整数对一组对象进行排序

我知道这是一个解决方案,它是有效的:

NSSortDescriptor *mySortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"from" ascending: YES comparator:^(id obj1, id obj2)
{
   if ([obj1 integerValue] > [obj2 integerValue])
   {
       return (NSComparisonResult) NSOrderedDescending;
   }

   if ([obj1 integerValue] < [obj2 integerValue])
   {
       return (NSComparisonResult) NSOrderedAscending;
   }

   return (NSComparisonResult) NSOrderedSame;
}];

self.myObjects = [[self.data allObjects] sortedArrayUsingDescriptors: @[mySortDescriptor]];
然后将其传递给我的
NSFetchRequest

在这段代码中,200出现在21之前。

用于(基于SQLite的)核心数据获取请求的排序描述符只能使用持久属性和一组有限的内置选择器,而不能使用像这样的Objective-C方法
integerValue

在这种情况下,
integerValue
似乎只是被忽略了,因此
from
值 按字符串排序,而不是按数字排序

如果无法将属性类型更改为“整数”(这也可以解决问题) 然后,您可以使用特殊选择器作为解决方法:

NSSortDescriptor *mySortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"from"
                                  ascending:YES
                                   selector:@selector(localizedStandardCompare:)];
localizedStandardCompare
是“类似查找器的排序”并对包含数字的字符串进行排序
根据它们的数值。

这是您的实际代码吗?它应该是
sortDescriptorWithKey:@“from.integerValue”
。当然,我修复了代码。(旁注:通过键路径访问属性是“键值编码”,而不是“键值编码”)
NSSortDescriptor *mySortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"from"
                                  ascending:YES
                                   selector:@selector(localizedStandardCompare:)];