【问题标题】:Looping Through Table View Cells循环遍历表视图单元格
【发布时间】:2012-08-18 03:33:30
【问题描述】:
for(NSUInteger j = 0 ; j < [sports count] ; j++){

    NSIndexPath *loopPath = [NSIndexPath indexPathWithIndex:j]; 

    if([pickerTable cellForRowAtIndexPath:loopPath].accessoryType == UITableViewCellAccessoryCheckmark){

        [chosenSports addObject:[pickerTable cellForRowAtIndexPath:loopPath].textLabel.text];                          

    }

}

此代码会产生 sigabrt 错误。确切的错误是“与 UITableView 一起使用的索引路径无效。传递给表视图的索引路径必须恰好包含两个指定部分和行的索引。如果可能,请使用 UITableView.h 中 NSIndexPath 上的类别。”提前致谢;

【问题讨论】:

    标签: objective-c ios


    【解决方案1】:

    错误是正确的。 NSIndexPaths 由一行和一个节号组成,考虑到它们实际上对您的实现是多么盲目(考虑到它们依赖于数据源和委托),对于表视图尤其如此。你有一个简单的初始化错误,试试这个:

    for(NSUInteger j = 0 ; j < [sports count] ; j++){
    
        NSIndexPath *loopPath = [NSIndexPath indexPathForRow:j inSection:0]; 
    
        if([pickerTable cellForRowAtIndexPath:loopPath].accessoryType == UITableViewCellAccessoryCheckmark){
    
            [chosenSports addObject:[pickerTable cellForRowAtIndexPath:loopPath].textLabel.text];                          
    
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      除了@CodaFi 的回答,您还应该知道cellForRowAtIndexPath 会为当前不可见的行返回nil

      因此,您的循环仅添加当前可见单元格中的对象,这可能不是您想要的。

      【讨论】:

      • 这就是为什么循环遍历表格视图中的单元格应该在数据源级别而不是表格视图本身进行。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 2021-06-28
      相关资源
      最近更新 更多