【发布时间】:2020-01-06 04:27:39
【问题描述】:
我得到了以下格式的字典:
[
{
"position": "1",
"name": "Jaen",
"group": "Student",
"Address": "Delhi"
},
{
"position": "2",
"name": "Jaen",
"group": "Student",
"Address": "Delhi"
},
{
"position": "1",
"name": "Jaen",
"group": "Teacher",
"Address": "Delhi"
}
]
基本上,我想围绕名为“group”的键对它们进行分组。我必须创建一个以下格式的字典来在我的 UI 中填充数据。
[
{
"Student": [
{
"position": "1",
"name": "Jaen",
"group": "Student",
"Address": "Delhi"
},
{
"position": "2",
"name": "Jaen",
"group": "Student",
"Address": "Delhi"
}
],
"Teacher": [
{
"position": "1",
"name": "Jaen",
"group": "Teacher",
"Address": "Delhi"
}
]
}
]
应该保持小组的顺序,即学生应该在老师之前。但是当我打印 dictGroupField 时,它会根据顺序给出随机结果。
我怎样才能维持秩序?
请在下面找到我正在使用的代码:
@property (strong, nonatomic) NSMutableDictionary *dictGroupField;
-(void)loadFieldData {
_dictGroupField = [[NSMutableDictionary alloc] init];
NSMutableArray *arrayFields = [self getArrayFields];
for (NSDictionary *dictT in arrayFields) {
NSString *strGroup = [dict valueForKey:@"group"];
if ([_dictGroupField valueForKey:strGroup] == nil) {
NSMutableArray *arrGroup = [[NSMutableArray alloc] init];
[arrGroup addObject:dict];
[_dictGroupField setObject:arrGroup forKey:strGroup];
} else {
NSMutableArray *arrGroupExist = [_dictGroupField valueForKey:strGroup];
[arrGroupExist addObject:dict];
[_dictGroupField setObject:arrGroupExist forKey:strGroup];
}
}
}
【问题讨论】:
-
字典根据定义是无序的。您可以使用具有
group属性的数组和自定义类,然后您可以按组对数组进行排序。并且不要使用valueForKey,除非你知道 KVC 是什么并且你真的需要 KVC。 -
您显示的格式不是字典它的字典数组。
标签: ios objective-c nsarray nsdictionary nsmutabledictionary