Sort a mutable array using a dictionary key

I already looked through several answers using various NSMutableArray sorting NSMutableArray , but for some reason they don't work for me.

I'm just trying to sort a modified array containing dictionaries with the Delay key in each dictionary. However, the sorted array is the 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 will not sort this mutable array that I initialize.

What am I doing wrong?

Here is 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 an array containing 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; } ) 
+6
source share
2 answers

The code above is good if I use NSNumber in my dictionary. This makes me think that the Delay value is stored as a string in the dictionary. What you will need to do is sorted by integerValue strings.

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

Try the following, it worked for 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]]; 
+1
source

Source: https://habr.com/ru/post/917396/


All Articles