【问题标题】:Protecting against cellForRowatIndexPath passing an index to an array that would be beyond its bounds防止 cellForRowatIndexPath 将索引传递给超出其范围的数组
【发布时间】:2014-07-02 02:20:22
【问题描述】:

这是我的问题:

假设我有 2 个UITableViewCell,每个单元格中有 Label1 和 Label2。 Label1 将在每个索引处连续接收一个值,因此 array[0] 和 array[1] != nil。 Label2 不是这种情况; Label2 在其数组 [0] 处接收一个值,但数组 [1] = nil。

这是我尝试过的最新方法,但是它并没有发现 array2 越界。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

      if (array1.count >= indexPath.row){
        UILabel *label1 = (UILabel *)[cell.contentView viewWithTag:1];
        NSString *label1String = [array1 objectAtIndex:indexPath.row];
        [label1 setText:label1String];

    }

    if (array2.count >= indexPath.row){
        UILabel *label2 = (UILabel *)[cell.contentView viewWithTag:2];
        NSString *label2String = [array2 objectAtIndex:indexPath.row];
        [label2 setText:label2String];

    }
}

【问题讨论】:

    标签: ios objective-c arrays uitableview


    【解决方案1】:

    数组索引范围从0count-1,所以检查必须是

    if ( indexPath.row < array2.count )
    

    该行不允许等于计数。

    【讨论】:

    • @initWithQuestion - 您可以使用左上角的小复选标记将其标记为正确。
    • 我会尽快。计数器有 5 分钟 :( 我想知道 indexPath.row 是从 0 开始,还是从 1 作为初始值开始?
    • 一切都是基于0的
    猜你喜欢
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多