objective-c - iOS关于NSMutableArray保存UITableViewCell对象后,cell取值出现错乱,请问什么原因?
PHP中文网
PHP中文网 2017-04-17 17:44:27
0
1
365

将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中文网

认证高级PHP讲师

reply all(1)
巴扎黑

The problem has been solved, please answer it yourself.
The reason is that the cell stored in the array is essentially a pointer to the object. When the cell is reused, the pointer points to the object before reuse, and the value obtained is the value of the cell before reuse. Therefore, value confusion will occur. The solution is to store each attribute of the cell in an array separately, or to use a model in advance to reassign the value when reusing the cell.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template