【问题标题】:iPhone application crashes in didDeselectItemAtIndexPath of UICollectionViewiPhone 应用程序在 UICollectionView 的 didDeselectItemAtIndexPath 中崩溃
【发布时间】:2014-12-05 12:05:54
【问题描述】:

我在我的应用程序中实现了UICollectionView,当我从UICollectionView 中取消选择图像时,我将从NSMutableArray 中删除该UIImage。现在我的问题是,如果图像超过两个并且我取消选择该图像,那么我的应用程序就会崩溃。

得到错误是

由于未捕获的异常“NSRangeException”而终止应用程序,原因:“*** -[__NSArrayM removeObjectAtIndex:]: index 2 beyond bounds [0 .. 1]”

下面是我的代码

- (void)collectionView:(UICollectionView *)collectionView 
        didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [selectedImagesArray removeObjectAtIndex:indexPath.row];
}

我得到indexPath,它超出了那个数组。

【问题讨论】:

  • 在 didSelect 上做了什么?

标签: ios objective-c iphone nsmutablearray uicollectionview


【解决方案1】:

检查数组计数是否大于 indexPath.row 属性,然后删除或检查该索引是否存在数组元素,如果存在则删除该元素

if(selectedImageArray[indexPath.row] != nil) {
   [selectedImagesArray removeObjectAtIndex:indexPath.row];
}

【讨论】:

    【解决方案2】:

    IndexPath 不一定有 row 属性,所以它可能是 nil。如果它是 nil,你会看到一个崩溃

    【讨论】:

      【解决方案3】:

      Indexpath.row 将返回您的实际数组的索引而不是选定的数组索引。 所以你必须在SelectedArray 中找到相同的元素,然后你也可以从选定的数组中删除该图像。

      举例

      实际的数组对象

      [1,2,3,4,5,6,7,8,9,10]

      从中选择对象

      [1,5,7]

      所以对象[1,5,7] 将处于选定状态,SelectedArray 也将处于。

      当您选择对象7 时,Indexpath.row 将返回您6

      并且您直接从 SelectedArray 中删除索引 6,这是不可用的,因此您会收到此错误。

      【讨论】:

        【解决方案4】:

        你必须使用 indexPath.item。 这通常在 collectionView 中使用。 IndexPath.row 用于 TableView。

        不管怎样,在它周围加上一个 if 条件来检查这个索引是否存在。

        【讨论】:

          【解决方案5】:

          添加这行代码来处理检查:

          if ([indexPath.row] < [selectedImagesArray count]) {
          
              [selectedImagesArray removeObjectAtIndex:indexPath.row];
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-06-20
            • 2011-06-16
            • 1970-01-01
            • 1970-01-01
            • 2012-03-07
            • 1970-01-01
            • 1970-01-01
            • 2016-01-25
            相关资源
            最近更新 更多