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

问题描述

这是放置在 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"}]
}]}

标签: iosobjective-ciphonensarraynsdictionary

解决方案


In cellForRowAtIndexPath: method, you can assign fetched value to text label in your cell like this:

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. In Modern Objective-C Syntax, you can access value of NSDictionary by dict[@""passenger_no"] instead of [dict valueForKey:@"passenger_no"].

Hope this helps!


推荐阅读