【问题标题】:UITableViewCell Data disappears after scrollUITableViewCell 滚动后数据消失
【发布时间】:2014-05-11 17:06:38
【问题描述】:

我在 arc 项目中有一个 tableView。当我滚动它一秒钟时,所有数据都会被隐藏或消失。

我通过 Strong 属性从另一个控制器传递数据。

CTableViewController* cTableVc=[[CTableViewController alloc] initWithNibName:@"CTableViewController" bundle:nil];
cTableVc.cArray=[[NSArray alloc] initWithArray:[MyVC pathForAllCardsInDocumentDiretory]];
cTableVc.view.frame=CGRectMake(0, 0, cTableVc.view.frame.size.width, cTableVc.view.frame.size.height);
[self.view addSubview:cTableVc.view];

这是我的财产

@property(strong, nonatomic) NSArray* cArray;

CTableViewController.m tableView 方法

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath   *)indexPath
{

NSString *CellIdentifier = @"CTableViewCell";
CTableViewCell *cell = (CTableViewCell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CTableViewCell" owner:self options:nil];
    for (id currentObject in topLevelObjects){
        if ([currentObject isKindOfClass:[UITableViewCell class]]){
            cell =  (CTableViewCell *) currentObject;
            break;
        }
    }
}

// Configure the cell...
NSString* strPath=[cArray objectAtIndex:indexPath.row];
cell.cardImageView.image=[UIImage imageWithContentsOfFile:strPath];
cell.cardNameLbl.text=[NSString stringWithFormat:@"My Card %d", arc4random() % 9];
cell.selectionStyle=UITableViewCellSelectionStyleNone;


return cell;
}

【问题讨论】:

  • 您的cellForRowAtIndex: 不会使用您在cArray 中的数据。为什么不呢?
  • 实际上它使用 i 删除了该行来创建简单性。编辑清楚。
  • 第一段代码中的[self.view cTableVc.view];是什么?
  • “所有数据都被隐藏或消失”是什么意思?你的意思是单元格变得完全空白?没有图片,标签上没有显示“我的卡 X”?
  • 您是否保留了对cTableVc 视图控制器的引用?只要将其视图作为当前视图控制器的子视图,就需要保持对视图控制器的强引用。更好的是,将视图控制器添加到当前视图控制器(参见 UIViewController 文档)。

标签: ios objective-c automatic-ref-counting uitableview


【解决方案1】:

问题在于您创建视图控制器并将新视图控制器的视图添加为子视图的代码。就目前而言,您不会保留对视图控制器的引用。所以视图控制器被释放,表没有委托或数据源。

正确的解决方案是利用UIViewController 容器方法并将新的视图控制器添加到当前视图控制器。

呼叫:

[self addChildViewController:cTableVc];

之后:

self.view addSubview:cTableVc.view];

请参阅UIViewController 的文档,因为除了这一行之外,还有更多工作要做。

【讨论】:

  • @rmaddy,谢谢。你拯救了我的一天。