1

我使用这个排序描述符

NSArray *sortedObjects = [self.array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES], nil]];

结果是 10 和 11 与 1 一起排序并放在 2 之前。

index is 1/12
index is 10/12
index is 11/12  
index is 2/12  
index is 3/12
index is 4/12
index is 5/12
index is 8/12
index is 9/12

如何避免这种情况?

4

2 回答 2

1

使用您自己的比较

- (NSArray *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr


其他允许自定义比较器的类型。

然后拆分日期并比较月份和日期。

于 2013-01-14T01:08:45.393 回答
0

我不知道那个类是你正在打印的项目,大概是字符串。发生这种情况是因为“/”字符的值高于“0”。

您必须使用自定义方法或块进行比较。所以还要初始化选择器,而不仅仅是键:

NSSortDescriptor* sd= [[NSSortDescriptor alloc]initWithKey: @"index" ascending: YES selector: @selector(customCompare:)];
NSArray *sortedObjects = [self.array sortedArrayUsingDescriptors: @[ sd ] ];

在您的 customCompare: 方法中,您应该比较对象。

于 2013-01-14T01:26:00.420 回答