[英]Sorting mutable array by dictionary key
我已经使用NSMutableArray
的各种排序方法查看了几个答案,但由于某种原因它们不适合我。
我只是试图通过每个字典中的Delay
键对包含字典的可变数组进行排序。 但是,“sorted”数组与原始数组完全相同。
顺便说一句,如果我创建一个虚拟可变数组并用包含数字的字典填充它,它可以正常工作,但由于某种原因它不会对我正在初始化的这个可变数组进行排序。
我究竟做错了什么?
这是我的代码:
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
排序。
NSSortDescriptor *delay =
[NSSortDescriptor sortDescriptorWithKey:@"Delay.integerValue" ascending:YES];
请尝试以下,它与我合作
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]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.