Reputation: 435
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;
}
)
Upvotes: 6
Views: 1130
Reputation: 57169
The code above is fine when I use NSNumber
s 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];
Upvotes: 8
Reputation: 21221
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]];
Upvotes: 1