0

嗨,我需要对获取结果进行排序,这是我的代码

NSManagedObjectContext *context = [appDelegate managedObjectContext]; 

NSError *error1;
NSEntityDescription *entityDesc;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
entityDesc=[NSEntityDescription entityForName:@"SubCategoryEntity" inManagedObjectContext:context];
[fetchRequest setEntity:entityDesc];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                            initWithKey:@"subCategoryId" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
NSArray *array = [context executeFetchRequest:fetchRequest error:&error1];

在这里我使用“子类别”字符串类型,所以它以“个位数”显示正确的顺序,但它不能以“双位数”工作

这是我在数“11”“9”,“8”,“7”,“6”,“5”,“4”,“3”,“2”,“1”,“10”后得到的订单, “0”

在这里我需要显示 "10","9","8","7","6","5","4","3","2","1","0"

我不知道为什么会发生任何人都可以帮助我

感谢提前。

4

1 回答 1

1

您以这种方式获得订单,因为这就是字符串排序的工作方式。您可以尝试在自定义类中使用NSSortDescriptorwith custom compareSubCategoryId:selector for .SubCategorySubCategoryEntity

更新

像这样初始化您的排序描述符:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"subCategoryId" 
                                                           ascending:NO
                                                            selector:@selector(compareSubCategoryId:)];

然后向您的自定义NSManagedObject子类添加一个方法:

- (NSComparisonResult)compareSubCategoryId:(id)otherObject {
  int ownSubCatId = [[self subCategoryId] intValue];
  int otherSubCatId = [[otherObject subCategoryId] intValue];

  if (ownSubCatId < otherSubCatId) return NSOrderedAscending;
  if (ownSubCatId > otherSubCatId) return NSOrderedDescending;
  return NSOrderedSame;
}
于 2012-06-05T09:23:00.443 回答