如何从具有多个数组的字典中获取特定键并存储到放置在表格视图单元格中的字符串中

Posted

技术标签:

【中文标题】如何从具有多个数组的字典中获取特定键并存储到放置在表格视图单元格中的字符串中【英文标题】:How to fetch a specific key from a dictionary having multiple arrays and store into string placed in table view cell 【发布时间】:2018-06-14 07:32:38 【问题描述】:

这是放置在tableView单元格中的标签,名称为a,b,c,d

//Want to store passenger_no here
    cell.a.text; 
//Want to store depart_city here
    cell.b.text; 
//Want to store name here
cell.d.text; 

这里是获取 JSON 数据并存储到名称数组的数组中,并将该数组存储到名为 dict 的字典中

NSArray *array = [_json valueForKey:@"result"];
NSDictionary *dict = array[indexPath.row];

JSON 看起来像这样:

 "result": [
         "passenger_no": 4,
          "destination_detail": [
                 "depart_city": "Indira Gandhi International"],
          "aircraft_info": [ "name": "CEAT 450"]
]

【问题讨论】:

【参考方案1】:

cellForRowAtIndexPath: 方法中,您可以将获取的值分配给单元格中的文本标签,如下所示:

NSArray *array = [_json valueForKey:@"result"];
NSDictionary *dict = array[indexPath.row];

//Want to store passenger_no here
cell.a.text = [dict valueForKey:@"passenger_no"];

//Want to store depart_city here
NSArray *destinationDetails = [dict valueForKey:@"destination_detail"];
NSDictionary *departcityInfo = destinationDetails.firstObject;
cell.b.text = [departcityInfo valueForKey:@"depart_city]"

//Want to store name here
NSArray *aircraftInfoList = [dict valueForKey:@"aircraft_info"];
NSDictionary *aircraftInfo = aircraftInfoList.firstObject;
cell.d.text = [aircraftInfo valueForKey:@"name"];

PS.现代Objective-C语法中,您可以通过dict[@""passenger_no"]而不是[dict valueForKey:@"passenger_no"]访问NSDictionary的值。

希望这会有所帮助!

【讨论】:

【参考方案2】:

所以在cellforrowatindexpath 你的代码将如下所示

NSDictionary *dict = array[indexPath.row];
    NSArray *destinationdetailarray = [dict valueForKey:@"destination_detail"];
    NSString *departcity = [[destinationdetailarray firstObject]valueForKey:@"depart_city"];
    NSString *passengerno = [NSString stringWithFormat:@"%@",[dict valueForKey:@"passenger_no"]];
    NSArray *aircraftinfo = [dict valueForKey:@"aircraft_info"];
    NSString *name = [[aircraftinfo firstObject]valueForKey:@"name"];

【讨论】:

以上是关于如何从具有多个数组的字典中获取特定键并存储到放置在表格视图单元格中的字符串中的主要内容,如果未能解决你的问题,请参考以下文章

如何将具有相同属性的所有字典从数组中获取到新数组?

遍历多个hashmap键并在jsp上显示[重复]

从每个键具有多个值的字典中将数据写入 csv

如何根据ios中的特定键从数组中获取字典

如何将数组内的对象和每个对象相乘,获取一个或多个键并减少它们的值?

在 CoreData 中存储和获取字典数组