当我在NSMutableDictionary中添加值时,它会自动设置Key wise。如何禁用它,并按照第一套第一套和第二套第二套进行排列。
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;
}有没有办法禁用按键排序?
发布于 2012-10-04 20:36:04
这里有一种方法:
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;发布于 2012-10-04 20:29:06
NSDictionary不会对键进行排序,字典中键的顺序没有定义,因为它是一个无序集合。
这意味着在获取/打印元素时不能信任元素的顺序,除非在获取元素时使用keysSortedByValueUsingSelector:或keysSortedByValueUsingComparator:对它们进行排序。
你也可以在allKeys的手册中看到这一点;
返回值
包含字典键的新数组,如果字典没有条目,则为空数组。
讨论
数组中元素的顺序为not。
在NSDictionary中没有办法保持键/值的顺序,所以如果你需要它们按照添加时的顺序排列,你基本上有两个选择;
NSArray等有序集合的同时,将它们添加到有序集合(如NSDictionary )中/从有序集合中删除它们,并使用该集合进行有序访问。keysSortedByValueUsingComparator:一起使用来对其进行排序。发布于 2012-10-04 20:26:39
NSDictionary不是用来排序的。您可以通过使用allKeys获取所有键并根据您的喜好对数组进行排序来对其进行排序。然后遍历该数组并获得相应的值。
https://stackoverflow.com/questions/12727176
复制相似问题