Sorting mutable array by dictionary key

无人久伴 提交于 2019-12-10 13:08:15

问题


I have already looked through a few answers using the various sorting methods of NSMutableArray, but for some reason they are not working for me.

I am just trying to sort the mutable array which contains dictionaries by the Delay key within each dictionary. However, the "sorted" array is the exact same as the original array.

By the way, it works fine if I create a dummy mutable array and populate it with dictionaries containing numbers, but for some reason it won't sort this mutable array that I am initializing.

What am I doing wrong?

Here's my code:

playlistCalls = [[NSMutableArray alloc] initWithArray:[currentPlaylist objectForKey:@"Tunes"]];

NSLog(@"original %@", playlistCalls);

NSSortDescriptor *delay = [NSSortDescriptor sortDescriptorWithKey:@"Delay" ascending:YES];
[playlistCalls sortUsingDescriptors:[NSArray arrayWithObject:delay]];

NSLog(@"sorted %@", playlistCalls);

Here's the array containing the dictionaries:

2012-06-04 15:48:09.129 MyApp[57043:f503] original (
        {
        Name = Test Tune;
        Delay = 120;
        Volume = 100;
    },
        {
        Name = Testes;
        Delay = 180;
        Volume = 100;
    },
        {
        Name = Testing;
        Delay = 60;
        Volume = 100;
    }
)

2012-06-04 15:48:09.129 MyApp[57043:f503] sorted (
        {
        Name = Test Tune;
        Delay = 120;
        Volume = 100;
    },
        {
        Name = Testes;
        Delay = 180;
        Volume = 100;
    },
        {
        Name = Testing;
        Delay = 60;
        Volume = 100;
    }
)

回答1:


The code above is fine when I use NSNumbers in my dictionary. That leads me to believe that the Delay value is stored as strings in your dictionary. What you will need to do then is sort by the strings integerValue.

NSSortDescriptor *delay = 
   [NSSortDescriptor sortDescriptorWithKey:@"Delay.integerValue" ascending:YES];



回答2:


Please try the following, it worked with me

NSDictionary *dic;
NSMutableArray *arr = [[NSMutableArray alloc] init];

dic = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithInt:120], @"Delay",
        [NSNumber numberWithInt:100], @"Volume",
       nil];
[arr addObject:dic];

dic = [NSDictionary dictionaryWithObjectsAndKeys:
       [NSNumber numberWithInt:160], @"Delay",
       [NSNumber numberWithInt:100], @"Volume",
       nil];
[arr addObject:dic];

dic = [NSDictionary dictionaryWithObjectsAndKeys:
       [NSNumber numberWithInt:100], @"Delay",
       [NSNumber numberWithInt:100], @"Volume",
       nil];
[arr addObject:dic];

NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@"Delay" ascending:YES];
[arr sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];


来源:https://stackoverflow.com/questions/10887490/sorting-mutable-array-by-dictionary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!