首頁  >  問答  >  主體

objective-c - iOS关于NSMutableArray保存UITableViewCell对象后,cell取值出现错乱,请问什么原因?

将UITableViewCell对象cell添加进NSMutableArray后,后续取值时,cell的textLable的text属性出现错乱,与cell本来的textLable的text不同,这是什么原因造成的呢?

比如:

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * timeRing = @"ring";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:timeRing];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:timeRing];
    }else{
        while ([cell.contentView.subviews lastObject]!=nil) {
            [[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    if (self.cellArray.count<self.ringArray.count) {
        
        
        self.timeRingItem = self.ringArray[indexPath.row];
        cell.tintColor = [UIColor redColor];
        cell.textLabel.text= self.timeRingItem.ringName;
        [self.cellArray addObject:cell];
    }
    else{
        
        cell = self.cellArray[indexPath.row];
     
    }
    
    return  cell;
}

这种情况下cell = self.cellArray[indexPath.row];就会失效,取出来的值是错乱的

PHP中文网PHP中文网2721 天前333

全部回覆(1)我來回復

  • 巴扎黑

    巴扎黑2017-04-17 17:46:27

    問題已解決,自己來回答一下吧。
    原因是數組儲存的cell是其實質是指向對象的指針,當復用cell時,指針指向的是複用前的對象,所得到的值是複用前的cell的值。所以就會出現值錯亂狀況,解決方法是把cell的各個屬性單獨存進數組中,或是提前用一個模型在復用cell時重新賦值一遍。

    回覆
    0
  • 取消回覆