0

I have to sort this array in descening order with the key "likecount". How can I sort it by specific key? This text is my output which coming on console:

source id key is (
    {

    2 = likecount;
    "This wall post is not from application. Direct from website." = message;
},

    {
    0 = likecount;
    "New integration" = message;
},
    {
    1 = likecount;
    "This is beta testing.. yes" = message;
},

    {
    2 = likecount;
    "hello wall testing.." = message;
}

)

I tried this below code but not getting any result. Still output is without sorted.

NSSortDescriptor *descriptor=[[NSSortDescriptor alloc]initWithKey:@"likecount" ascending:YES];
NSArray *sortdescriptor=[NSArray arrayWithObject:descriptor];
NSArray *sortedarray=[array sortedArrayUsingDescriptors:sortdescriptor];


  NSLog(@"source sorting id key is %@",sortedarray);
 NSLog(@"source s@@@@@@  id key is %@",array);

// array is variable which is holding actual content

Ajay_Kumar
  • 1,381
  • 10
  • 34
  • 62
  • I tried by this link but not getting output. I might be my error. http://stackoverflow.com/questions/1844031/how-to-sort-nsmutablearray-using-sortedarrayusingdescriptors – Ajay_Kumar Jun 27 '11 at 12:33

2 Answers2

0

An NSSortDescriptor should work for you. Try something like this

NSSortDescriptor *sortd = [[[NSSortDescriptor alloc] initWithKey:@"likecount"
                                           ascending:NO] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortd];
sortedArray = [sourceArray sortedArrayUsingDescriptors:sortDescriptors];
Joe
  • 56,979
  • 9
  • 128
  • 135
  • I implemented above code but nothing happening on data. Here is my code. NSSortDescriptor *sortd = [[[NSSortDescriptor alloc] initWithKey:@"likecount" ascending:YES] autorelease]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortd]; NSLog(@"source sorting id key is %@",sortDescriptors); NSArray * sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors]; printing sortDescriptors key is ( "(likecount, ascending, compare:)" ) and remaining output is same. – Ajay_Kumar Jun 27 '11 at 12:46
  • What does your collection consist of? custom classes? dictionary? – Joe Jun 27 '11 at 14:31
0

You could do this using below code:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"likecount" ascending:YES];
[self.msgHistory sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];   

[descriptor release];
Ajay Sharma
  • 4,509
  • 3
  • 32
  • 59