Populate tableview from NSDictionary

孤者浪人 提交于 2019-12-03 09:00:58

Yes you can use a single array. The trick is to create an array with each array entry holding a dictionary. Then you query the array to populate your tableview.

E.g.: If your array is a property called tableData and you have custom tableview cell called CustomCell then your code might look something like the following:

- (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;
}

Similarly, if you have multiple sections in your tableview then you will construct an array of arrays, with each sub-array containing the dictionaries for that section. The code to populate the tableview would look something similar to the following:

- (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; Take your dictionaries created from your JSON data and put them in an array. Then query the array to populate the tableview.

You can do as follows:

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

Then in cellForRowAtIndexPath do as follows:

NSDictionary *obj = [main_data objectAtIndex: indexPath.row];
// Access values as follows:
[obj objectForKey: @"Id1"]
[obj objectForKey: @"lat"]
...
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!