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

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];就会失效,取出来的值是错乱的


问题已解决,自己来回答一下吧。
原因是数组中存储的cell是其实质是指向对象的指针,当复用cell时,指针指向的是复用前的对象,所得到的值是复用前的cell的值。所以就会出现值错乱情况,解决办法是把cell的各个属性单独存进数组中,或是提前用一个模型在复用cell时重新赋值一遍。

【热门文章】
【热门文章】