我正在将字典作为JSON响应
Lease = {
"KINDERSLEY KERROBERT" =
(
{
"lease_code" = 37;
},
{
"lease_code" = 38;
}
);
LLOYDMINSTER =
(
{
"lease_code" = 68;
},
{
"lease_code" = 69;
}
);
"SOUTHEASTERN SASKATCHEWAN" =
(
{
"lease_code" = 1;
},
{
"lease_code" = 2;
}
);
"SWIFT CURRENT" =
(
{
"lease_code" = 32;
},
{
"lease_code" = 33;
}
);
};
我想按如下方式对其进行排序:
Lease = {
"SOUTHEASTERN SASKATCHEWAN" =
(
{
"lease_code" = 1;
},
{
"lease_code" = 2;
}
);
"SWIFT CURRENT" =
(
{
"lease_code" = 32;
},
{
"lease_code" = 33;
}
);
"KINDERSLEY KERROBERT" =
(
{
"lease_code" = 37;
},
{
"lease_code" = 38;
}
);
LLOYDMINSTER =
(
{
"lease_code" = 68;
},
{
"lease_code" = 69;
}
);
};
我在下面编写代码来对字典进行排序:
- (NSArray *)sortKeysByIntValue:(NSDictionary *)dictionary {
NSArray *sortedKeys = [dictionary keysSortedByValueUsingComparator:^NSComparisonResult(NSArray *obj1, NSArray *obj2) {
NSString* key1 = [[obj1 objectAtIndex:0] objectForKey:@"lease_code"];
NSString* key2 = [[obj2 objectAtIndex:0] objectForKey:@"lease_code"];
return [key1 compare:key2];
}];
return sortedKeys;
}
它为我提供了我想要的sortKeys,但在使用以下代码重建NSMutableDictionary
之后:
NSArray *sortedKeys = [self sortKeysByIntValue:dictionary];
NSMutableDictionary *sortedDictionary = [[NSMutableDictionary alloc] init];
for (NSString *key in sortedKeys) {
[sortedDictionary setObject:dictionary[key] forKey:key];
}
它再次未按照回复显示。
请帮帮我
答案 0 :(得分:3)
词典总是未分类的。它们用作查找数据的键值存储。您应该将数据的顺序与字典分开。您需要已有的词典和键的排序数组。
@property NSDictionary *dataDict;
@property NSArray *sortedKeys;
self.sortedKeys = [self sortKeysByIntValue:self.dataDict];
在UITableViewDataSource
方法中,首先使用索引查询数组,获取密钥,然后从字典中检索数据。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = [indexPath row];
NSString *key = [self.sortedkeys objectAtIndex:row];
NSObject *dataObject = [self.dataDict valueForKey:key];
答案 1 :(得分:1)
NSArray *sortedKeys = [self sortKeysByIntValue:dictionary];
NSMutableArray* values = [NSMutableArray array];
for (NSString* key in sortedKeys)
{
[values addObject:dictionary[key]];
}
现在您已经对键和值进行了排序。这正是您所需要的