困扰很久的一个 bug, help!

2017-04-18 11:51:26 +08:00
 acumen

关于 UICollectionView 的一个问题。UICollectionView 嵌套在 UITableViewCell 中。问题就是以下一段简单的代码,但是线上 [self.feed.blog.imageInfos objectAtIndex:indexPath.row] 这里经常出现数组越界,很奇怪!! indexPath 的 bound 不是上面的 collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 这个函数约束了吗,为什么会越界。

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {
    return count = self.imageInfos.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LKMImageInfo *imageInfo = [self.imageInfos objectAtIndex:indexPath.row];
    
    ...
    
    return imageCell;
}
5490 次点击
所在节点    iDev
7 条回复
anerevol
2017-04-18 12:39:03 +08:00
有在其他线程改变 self.imageInfos 的值么 如果有的话,把这个操作放主线程试试
acumen
2017-04-18 15:42:14 +08:00
@anerevol 都是在主线程操作的,困扰很久在于这个 bug 很难复现,但是线上 crash log 里却很多。。。
zhongdong
2017-04-18 15:44:46 +08:00
放在 tableView 的 cell 里,排除一下是不是复用 cell 造成的?有没有及时更新都应 cell 里的 imageInfos ?
linKnowEasy
2017-04-18 16:21:24 +08:00
1. 确认一下 section 是不是只有一个
2. self.imageInfos, 哪里被修改了之后。 没有调用 collectionView . reload 代码。
3. 这个 bug 很难复现, 感觉很大可能就是 修改 imageInfos 值相关代码的线程问题??.
ps. 暂时只想到了这几种可能。
HelloiWorld
2017-04-18 17:43:40 +08:00
楼上说的是对的,有遇到类似问题,嵌套时发现它读取的仍然是修改前的数组,当时 count 不为 0 所以进了 cellFor 方法
我一个过渡的办法是 修改数组或有任何赋值操作前 先将数组清空,然后调用 reloadData 方法, 然后再做修改赋值操作,再调用 reloadData 方法。
c447279704
2017-04-26 10:13:28 +08:00
numberOf 和 cellfor 之间是很有可能改变 model 的,加个越界保护吧
BB9z
2017-04-29 21:30:13 +08:00
UICollectionView 发生操作到访问可能 data source 有一个延迟,这点和 UITableView 不同。

像这样的逻辑,是可能崩溃的。

UICollectionView *cv = ...;
[cv insertItemsAtIndexPaths:...];
[dataSource insertObject:... atIndex:...];

如果不用 reloadData 强制刷新,需要用 performBatchUpdates:completion: 来保护。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/355588

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX