2013-04-29 84 views
0

我正在使用Coredata和NSFetchedResultsController存储和检索值并在表格视图中显示它们。我在cellForRowAtIndexPath中创建自定义标签并显示属性'lastname'的值。但我收到错误的价值。UILabel在UITableView中显示错误的值

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
UILabel *label = nil; 
if(cell == nil){ 
    cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]autorelease]; 
    label = [[[UILabel alloc]initWithFrame:CGRectMake(160,10,120,21)]autorelease]; 
    label.backgroundColor = [UIColor clearColor]; 
    [cell.contentView addSubview:label]; 

    //Configure the cell 
    List *list = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
    label.text = list.lastname; 

} 
[self configureCell:cell atIndexPath:indexPath]; 
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
cell.selectionStyle = UITableViewCellSelectionStyleGray; 
return cell; 
} 

的奇怪的是,它是工作正常,如果我除去UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];线和如果条件。

回答

0

你需要移动以外的

if(cell == nil) 

原因是

label.text = list.lastname; 

,该if(cell == nil)内的内容将被调用只有x次,其中x是可见的数屏幕上的细胞。当你滚动时,新单元格正在被重用,这就是为什么它们包含一些不正确的值。

编辑:

您还需要将您的

List *list = [self.fetchedResultsController objectAtIndexPath:indexPath]; 

if之外。

编辑2:

这是应该的样子:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
UILabel *label = nil; 
if(cell == nil){ 
    cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]autorelease]; 
    label = [[[UILabel alloc]initWithFrame:CGRectMake(160,10,120,21)]autorelease]; 
    label.backgroundColor = [UIColor clearColor]; 
    label.tag=1; 
    [cell.contentView addSubview:label]; 


} 
[self configureCell:cell atIndexPath:indexPath]; 

//Configure the cell 
List *list = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
label = (UILabel*)[cell.contentView viewWithTag:1]; 
label.text = list.lastname; 

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
cell.selectionStyle = UITableViewCellSelectionStyleGray; 
return cell; 
} 

这应该为你工作

+0

仍然没有工作 – 2013-04-29 14:26:29

+0

编辑我的答案。这应该现在工作 – gasparuff 2013-04-29 14:27:05

+0

把它放在你的'[self configureCell:cell atIndexPath:indexPath];' – gasparuff 2013-04-29 14:27:40