Question

My NSArray contains NSDictionary instances, and in the dictionaries I have orderid. I want to make them sort in descending order. But it is not sorting.

I have tried this code

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"orderid" ascending:FALSE];
[self.orderArray sortUsingDescriptors:[self.orderArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];

And this code :

 [self.orderArray sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"orderid" ascending:NO]]];

But it didn't worked.

Here is the log

orders : (
        {
        orderid = 6739;
    },
        {
        orderid = 6740;
    },
        {
        orderid = 6745;
    },
        {
        orderid = 6746;
    },
        {
        orderid = 6748;
    },
)
Was it helpful?

Solution 2

I am agree with the @HotLicks this code must work. Are you sure between the sort code and log there is no code. If there is than please add it.

Only problem i see is that You have added your array name instead of NSArray in [self.orderArray sortUsingDescriptors:[self.orderArray arrayWithObject:sortDescriptor]]; this line.

Do it like this :

 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"orderid" ascending:FALSE];
 [self.orderArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; //Change in this line
 [sortDescriptor release];

 NSLog(@"self.orderArray : %@",self.orderArray);

OTHER TIPS

This should work

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"orderid.intValue" ascending:NO ];
 [self.orderArray sortUsingDescriptors:@[sortDescriptor]];

You can sort an array using your "custom" comparator.

NSMutableArray *nds = [[NSMutableArray alloc] initWithArray:nodes];
//
[nds sortUsingComparator:^NSComparisonResult(Node *f1,Node *f2){
    if (f1.nodeType == FOLDER && f2.nodeType == FILE) {
        return NSOrderedAscending;
    } else if (f1.nodeType == FILE && f2.nodeType == FOLDER) {
        return NSOrderedDescending;
    } else if (f1.nodeType == f2.nodeType) {
        return [f1.displayName localizedCaseInsensitiveCompare:f2.displayName];
    }
    //
    return [f1.displayName compare:f2.displayName];
}];

This method will traverse the array, taking two objects from the array and comparing them.
The advantage is that the objects can be of any type (class) and you decide the order between the two. In the above example I want to order:
- folders before files
- folders and files in alphabetical order

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top