是的,您可以使用单个数组。诀窍是创建一个数组,其中每个数组条目都包含一个字典。然后你查询数组来填充你的tableview。
例如:如果您的数组是一个名为的属性tableData
,并且您调用了自定义 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 的代码类似于以下内容:
- (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;博士; 获取从 JSON 数据创建的字典并将它们放入一个数组中。然后查询数组以填充 tableview。