通过字典键对可变数组进行排序 [英] Sorting mutable array by dictionary key
问题描述
我已经使用NSMutableArray
的各种排序方法仔细查看了一些答案,但是由于某些原因,它们对我不起作用.
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.
我只是想通过每个字典中的Delay
键对包含字典的可变数组进行排序.但是,排序"数组与原始数组完全相同.
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.
我在做什么错了?
这是我的代码:
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);
这是包含字典的数组:
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;
}
)
推荐答案
当我在字典中使用NSNumber
时,上面的代码很好.这使我相信Delay
值作为字符串存储在字典中.然后,您需要做的是按字符串integerValue
排序.
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];
这篇关于通过字典键对可变数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!