Chithri Ajay
Chithri Ajay

Reputation: 917

How to sorting core data fetch result

hi i need to sort fetch result deasending order here is my code

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];

here i use "subcategory" string type so it show me correct order in "single digits" but it couldn't work in "double digits"

here is i get order after count "11" "9","8","7","6","5","4","3","2","1","10","0"

here i need to show "10","9","8","7","6","5","4","3","2","1","0"

i don't why it's happing can any one help me

Thanks for advance.

Upvotes: 0

Views: 199

Answers (1)

Eimantas
Eimantas

Reputation: 49335

You're getting the order in this way because this is how sorting of strings work. You can try using NSSortDescriptor with custom compareSubCategoryId: selector in your custom SubCategory class for SubCategoryEntity.

update

Initialize your sort descriptor like this:

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

Then add a method to your custom NSManagedObject subclass:

- (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;
}

Upvotes: 1

Related Questions