从NSDictionary填充tableview

我有一个从一个JSON请求收到一个NSDictionary看起来像这样:

RESULT : ( { Id1 = 138; lat = "45.5292910"; long = "-73.6241500"; order = "2343YY3" }, { Id1 = 137; lat = "45.5292910"; long = "-73.6241500"; order = "2343YY3" }, etc. 

我想显示它在一个TableView(CellforRowAtIndexPath),所以我得到的数据作为NSArray。 该方法似乎效率低下,因为每个键Id1latlong等等被创build为一个NSArray,以便我可以显示他们每个: [self.data1 objectAtIndex:indexPath.row]; [self.data2 objectAtIndex:indexPath.row]

如何在不创build和使用4个NSArrays的情况下实现同样的目标? 我可以使用单个NSArray或存储数据的NSMutableDictionary吗?

更新:

当TableView加载时,它最初是空的,但我有一个相同的VC加载窗体的模式视图的button。 当我加载表单,然后解散它返回到TableView,数据被加载! 你能提出我缺less的东西吗?

是的,你可以使用一个单一的数组。 诀窍是创build一个数组与每个数组条目持有一个字典。 然后你查询数组来填充你的tableview。

例如:如果你的数组是一个名为CustomCell的属性,并且你有定制的tableview单元格叫做CustomCell那么你的代码可能如下所示:

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [self.tableData count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"CustomCell"; CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; // Configure the cell... cell.latitude.text = [[self.tableData objectAtIndex:indexPath.row] objectForKey: @"lat"]; cell.longitude.text = [[self.tableData objectAtIndex:indexPath.row] objectForKey:@"long"]; // continue configuration etc.. return cell; } 

同样,如果在tableview中有多个部分,则将构造一个数组数组,每个子数组包含该部分的字典。 填充tableview的代码看起来类似于以下内容:

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return [self.tableData count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [[self.tableData objectAtIndex:section] count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"CustomCell"; CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; // Configure the cell... cell.latitude.text = [[[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey: @"lat"]; cell.longitude.text = [[[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"long"]; // continue configuration etc.. return cell; } 

TL; DR; 把你的JSON数据创build的字典放在一个数组中。 然后查询数组来填充tableview。

你可以这样做:

 // main_data = Store your JSON array as "array of dictionaries" 

然后在cellForRowAtIndexPath执行如下操作:

 NSDictionary *obj = [main_data objectAtIndex: indexPath.row]; // Access values as follows: [obj objectForKey: @"Id1"] [obj objectForKey: @"lat"] ... ...