如何禁用NSDictionary自动按键排序 [英] How to Disable NSDictionary Sort automatically key wise
本文介绍了如何禁用NSDictionary自动按键排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我在 NSMutableDictionary
中添加值时,它会自动设置Key wise。如何禁用它并按照第一组第一和第二组排列。
When I add values in NSMutableDictionary
it automatically set Key wise. How can i disable it and arrange as per first set first and second set second.
NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
[filteredDictionary setObject:@"abc" forKey:@"1"];
[filteredDictionary setObject:@"abc" forKey:@"3"];
[filteredDictionary setObject:@"abc" forKey:@"2"];
[filteredDictionary setObject:@"abc" forKey:@"5"];
[filteredDictionary setObject:@"abc" forKey:@"4"];
NSLog(@"%@",filteredDictionary);
current output:
{
1 = abc;
2 = abc;
3 = abc;
4 = abc;
5 = abc;
}
but i want
{
1 = abc;
3 = abc;
2 = abc;
5 = abc;
4 = abc;
}
有没有办法按密钥禁用排序?
Is there any way to disable sorting as per key?
推荐答案
这是一种方法:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"key" ascending:YES comparator:^(id obj1, id obj2) {
if (obj1 > obj2) {
return (NSComparisonResult)NSOrderedDescending;
}
if (obj1 < obj2) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
NSArray *sortedKeys = [[filteredDictionary allKeys] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSMutableDictionary *orderedDictionary = [NSMutableDictionary dictionary];
for (NSString *index in sortedKeys) {
[orderedDictionary setObject:[filteredDictionary objectForKey:index] forKey:index];
}
filteredDictionary = orderedDictionary;
这篇关于如何禁用NSDictionary自动按键排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文