2012-03-26 37 views
0

我有一個UITableView,我想從一個對象數組中填充細節。 tableview在每一行顯示相同的項目(正確的行數雖然!)我知道這一定是一個容易的 - 但我不明白我出錯的地方:我的UITableView在每一行顯示相同的項目

初始化的代碼片段表中的數據:

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

...並加載在接下來的視圖中的表的代碼...

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

回答

3

移動這樣的:

tank *thisTank = [[tank alloc] init]; 

在for循環中。你一遍又一遍地更新同一個對象。

此外,你的初始化錯誤的細胞 - 使用指定的初始化器,並通過在重用標識,否則你將創造新細胞的所有時間:

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

你真的應該遵循objective- c命名約定。課程以大寫字母開頭,其他內容以小寫字母開頭。無論如何,它使得你的代碼更容易閱讀。

+0

完美!謝謝!我認爲這會很容易! :-)我認爲通過初始化循環外的坦克我只需更改值並有效添加對象的副本......再次感謝! :-) – HillInHarwich 2012-03-26 10:10:53

0

每次刷新表格!!!

[self.tableView reloadData];

相關問題