我有一个 UITableView,我想用对象数组中的详细信息填充它。 tableview 在每一行上显示相同的项目(虽然行数正确!)我知道这一定很简单 - 但我看不出哪里出错了:
初始化表数据的 View 代码片段:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:@"Show Tank List"])
{
NSURL *myUrl = [[NSURL alloc]initWithString:@"http://localhost/~stephen-hill9/index.php"];
NSData *data = [[NSData alloc] initWithContentsOfURL:myUrl];
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
int i;
NSMutableArray *tanksList;
tank *thisTank = [[tank alloc] init];
tanksList = [[NSMutableArray alloc] init];
for (i=0; i<json.count; i++) {
NSDictionary *bodyDictionary = [json objectAtIndex:i];
thisTank.tankNumber = [bodyDictionary objectForKey:@"ID"];
thisTank.tankProduct = [bodyDictionary objectForKey:@"Product_Desc"];
thisTank.tankPumpableVolume = [bodyDictionary objectForKey:@"Pumpable"];
[tanksList addObject:thisTank];
}
[segue.destinationViewController setTanks:tanksList];
}
}
...以及在下一个 View 中加载表格的代码...
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;//keep this section in case we do need to add sections in the future.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.tanks count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Tank List Table Cell";
UITableViewCell *cell = [self.tankTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];
}
tank *thisTank = [self.tanks objectAtIndex:indexPath.row];
cell.textLabel.text = thisTank.tankNumber;
return cell;
}
最佳答案
移动这个:
tank *thisTank = [[tank alloc] init];
在你的 for 循环中。您一遍又一遍地更新同一个对象。
此外,您正在错误地初始化单元格 - 使用指定的初始化程序,并传入重用标识符,否则您将一直创建新单元格:
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
你真的应该遵循 objective-c 的命名约定。类以大写字母开头,其他一切以小写字母开头。无论如何,它使您的代码更易于阅读。
关于objective-c - 我的 UITableView 在每一行显示相同的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9870089/