user2452016
user2452016

Reputation:

Unable to sort array according to containing number

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;
    },
)

Upvotes: 0

Views: 109

Answers (3)

Johnykutty
Johnykutty

Reputation: 12839

This should work

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

Upvotes: 1

Dilip Manek
Dilip Manek

Reputation: 9143

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

Upvotes: 0

tagyro
tagyro

Reputation: 1679

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

Upvotes: 0

Related Questions