-2

I am new to iOS development. I am creating NSMutableDictionary with Title, Count, Score. Now I want to sort my NSMutableDictionary with the base of Count in Descending order. Please help me.

    self.top3_Question_Array = [[NSMutableArray alloc] init]; 

    NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
    [item setValue: [NSString stringWithFormat: itemName] forKey:@"Title"];
    [item setValue: [NSNumber numberWithInteger: itemCount] forKey:@"Count"];
    [item setValue: [NSNumber numberWithFloat: itemScore] forKey:@"Score"];


    [self.top3_Question_Array addObject: item1];
SHIDHIN TS
  • 1,557
  • 3
  • 26
  • 58
  • 1
    possible duplicate of [http://stackoverflow.com/questions/4558639/sort-an-nsmutabledictionary](http://stackoverflow.com/questions/4558639/sort-an-nsmutabledictionary) – PK20 Nov 27 '15 at 06:19
  • SHIDHIN please up vote and tick my answer if it is useful for you.Because others can get solution through your question also it can get more views. – user3182143 Nov 27 '15 at 06:57

2 Answers2

1

I tried below coding.it works fine for me

NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
[item setValue:[NSString stringWithFormat: itemName] forKey:@"Title"];
[item setValue: [NSNumber numberWithInteger: itemCount] forKey:@"Count"];
[item setValue: [NSNumber numberWithFloat: itemScore] forKey:@"Score"];

[top3_Question_Array addObject:item];


NSSortDescriptor *countDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Count" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObjects:countDescriptor, nil];
NSArray *sortedArrayOfDictionaries = [top3_Question_Array sortedArrayUsingDescriptors:descriptors];
NSLog(@"sorted array of dictionaries: %@", sortedArrayOfDictionaries);

Also the expected output is

  sorted array of dictionaries: (
    {
    Count = 2;
    Score = 30;
    Title = Cholate;
 }
)
user3182143
  • 9,459
  • 3
  • 32
  • 39
0

Try this code

NSArray *myArray = @[@{@"Title" : @"Hello", @"Count":@"3", @"Score":@"100"}, @{@"Title" : @"Hello", @"Count":@"2", @"Score":@"100"}, @{@"Title" : @"Hello", @"Count":@"1", @"Score":@"100"}, @{@"Title" : @"Hello", @"Count":@"4", @"Score":@"100"}];
    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"Count"
                                                                 ascending:NO
                                                                  selector:@selector(localizedCaseInsensitiveCompare:)];
    NSArray *sorted_array = [myArray sortedArrayUsingDescriptors:@[descriptor]];
    NSLog(@"sorted_array: %@", sorted_array);
Bandish Dave
  • 791
  • 1
  • 7
  • 27