Take the 2-minute tour ×

I'm having trouble sorting an NSNumber using NSSortDescriptor. For whatever reason it won't sort into the correct order. What am I doing wrong?

- (NSNumber *)sortNumber {

NSNumber *sum = [NSNumber numberWithFloat:([self.capacity floatValue] / [self.availability floatValue])];

return sum;

It is defined as an Int32 in the xcdataModel and called by this class to sort.

- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController == nil) {
    NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
	[fetchRequest setReturnsObjectsAsFaults:NO];  
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]];
    NSArray *sortDescriptors = nil; 
} if ([fetchSectioningControl selectedSegmentIndex] == 0) {
        sortDescriptors = [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"sortNumber" ascending:YES selector:@selector(compare:)] autorelease]];
[fetchRequest setSortDescriptors:sortDescriptors];

EDIT:Yeah, in the cold light of day this needs a little more explanation. I'll try to explain the project. This is a CoreData app, the values 'capacity' and 'availability' are derived from parsing an XML file with SAX and attaching them to the Managed Object Model where they are defined as Strings, originally they would have been numeric in the XML.

These are then defined in a Class where the calculation above has been made and attached to the same Object Model (if the code above is right then perhaps this is where the problem is?). All this has been in effort to obtain a percentage value that I would like to use to sort a TableView. (BTW, I realise they need swapping around, oops) The second bit of code is where this happens using NSFetchResultsController and ManagedObjectContext. I know this bit works because I'm also sorting this list by other attributes set to if selectedSegmentIndex == 0 etc. They all sort correctly.

I hope this makes a bit more sense.

share|improve this question
is this a CoreData app? could you please include a little more code to help us solve the problem? –  slf Sep 25 '09 at 3:10
I've tried adding more detail to the project, see above. As always with these sorts of things it's difficult to know where to stop. The Manage Object Model is difficult to post, but basically it has only one relationship attached which is not this criteria. Perhaps it should be? –  Jim Sep 26 '09 at 13:28

1 Answer 1

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sortNumber" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

[request setSortDescriptors:sortDescriptors];

you can use NSSortDescriptor without calling compare method. It will sort itself in you desired order.

share|improve this answer

Your Answer


