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

将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讲师

모든 응답(1)
巴扎黑

문제가 해결되었습니다. 직접 답변해 주세요.
그 이유는 배열에 저장된 셀은 본질적으로 객체에 대한 포인터이기 때문입니다. 셀을 재사용할 때 포인터는 재사용 전 객체를 가리키며, 얻은 값은 재사용 전 셀의 값입니다. 따라서 값의 혼란이 발생하게 됩니다. 해결 방법은 셀의 각 속성을 별도로 배열에 저장하거나 셀을 재사용할 때 미리 모델을 사용하여 값을 다시 할당하는 것입니다.

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!