我有一个 NSDictionary,它的键是一个国家/地区,对象是一个城市数组:
United States
New York
Portland
Austin
San Francisco
India
New Delhi
Belgium
Antwerp
Brussels
我想从这本字典创建一个字典,如下所示:
United States
4
Belgium
2
India
1
如此从最大键数到最小键数排序,新的键就是原字典中键的数量。这可能吗?什么是最有效的方法?
我走得最远的是使用
NSComparator sorter = ^NSComparisonResult(id a, id b)
{
NSArray* a1 = a;
NSArray* a2 = b;
if([a1 count] > [a2 count]) return NSOrderedAscending;
if([a1 count] < [a2 count]) return NSOrderedDescending;
return NSOrderedSame;
}
NSArray* ordered = [dictionary keysSortedByValueUsingComparator:sorter];
但是我只有一个有序数组,而不是附加到该数组的值。
提前致谢!
最佳答案
您需要创建一个具有 countryName
和 numberOfCities
成员的新类。完成此操作后,您可以创建这些对象的数组并对它们进行排序。
例如,自定义对象可以具有与此类似的头文件:
@interface Country : NSObject
@property (nonatomic, strong) NSString *countryName;
@property (nonatomic) NSUInteger numberOfCities;
@end
关于ios - 根据 key 值的数量对 NSDictionary 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17670730/