我只是想知道是否可以在 iOS 中对整数字典进行排序?查看前面的示例/问题,似乎大多数人都在对整数数组或字典数组(包含整数)进行排序。
但是,假设我有一本结构如下的字典:
{numWords = 12, numPhotos = 15, numFriends = 8}
键不一样,所以似乎我不能使用排序描述符(用键初始化),所以有没有办法对整数进行排序并保持关联的键完好无损?
我只是想知道是否可以在 iOS 中对整数字典进行排序?查看前面的示例/问题,似乎大多数人都在对整数数组或字典数组(包含整数)进行排序。
但是,假设我有一本结构如下的字典:
{numWords = 12, numPhotos = 15, numFriends = 8}
键不一样,所以似乎我不能使用排序描述符(用键初始化),所以有没有办法对整数进行排序并保持关联的键完好无损?
Dictionaries can't be sorted. But there is a method that will return an array of keys in order based on the values being sorted.
NSMutableDictionary *dict = ...; // your dictionary
NSArray *orderedKeys = [dict keysSortedByValueUsingSelector:@selector(compare:)];
In your case, orderedKeys
would be numFriends, numWords, numPhotos
.
To make use of the ordered keys you can do something like:
for (id key in orderedKeys) {
id value = [dict objectForKey:key];
}
NSDictionary are not ordered. And you never sort dictionary.
Indeed you sort keys and or values.
For your case:
You need to extract all the values into arrayValues parallely keys in arraykeys, sort based on arrayValues.
NSMutableArray *array1 = [NSMutableArray arrayWithObjects:[NSNumber numberWithInt:5], [NSNumber numberWithInt:3], [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:4], [NSNumber numberWithInt:6], nil];
NSMutableArray *arrayKeys = @[@"Five", @"Three", @"One", @"Two", @"Four", @"Six"];
NSMutableArray *arrayValues = @[@"Cinq", @"Trois", @"Un", @"Deux", @"Quatre", @"Six"];
[array1 sortArrayUsingSelector:@selector(compare:) withPairedMutableArrays:arrayKeys, arrayValues, nil];
After the call to sortArrayUsingSelector:withPairedArrays:, the three arrays will all be in numeric order, so arrayKeys will look like this:
One, Two, Three, Four, Five, Six
and arrayValues will look like this:
Un, Deux, Trois, Quatre, Cinq, Six
字典不可排序。
也就是说,您可以有两个排序数组,一个包含键,另一个包含关联的值。按值的顺序对它们进行排序。
NSDictionary *d = @{
@"numWords": @12,
@"numPhotos": @15,
@"numFriends": @8
};
NSComparisonResult (^cmp)(id, id) = ^(id obj1, id obj2) {
return [obj1 compare:obj2];
}
NSArray *keys = [d keysSortedByValueUsingComparator:cmp]
NSMutableArray *vals = [[id allValues] mutableCopy];
[vals sortUsingComparator:cmp];
假设对象是唯一的:
1) 向字典查询allValues的数组
2)对值数组进行排序
3)由于没有valueForKey,对于每个值,使用快速枚举或enumerateKeysAndObjectsUsingBlock:来找到合适的键。