我在视图顶部有一个自定义选项卡,用户可以来回切换两个视图。两个视图都包含动态填充来自服务器的数据的UICollectionView。据我了解,如果numberOfItemInSection
在调用[collectionView reloadData]
时返回0,则不会调用cellForItemAtIndexPath
。换句话说,如果调用cellForItemAtIndexPath
,则意味着源中存在一些数据。下面是我将一个视图切换到其他视图时使用的一些代码。
- (void)refresh
{
[self.collectionView setContentOffset:CGPointZero];
[self.data removeAllObjects];
[self.refreshControl beginRefreshing];
if (self.collectionView.contentOffset.y == 0) {
[UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^(void){
self.collectionView.contentOffset = CGPointMake(0, -MPViewHeight(self.refreshControl));
} completion:^(BOOL finished){
}];
}
[self.collectionView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
[self requestToServerAtIndex:0];
}
- (void) requestToServerAtIndex:(NSInteger)index
{
@weakify(self)
[[self.serverHelper getData:index requestCount:20] subscribeNext:^(id JSON) {
@strongify(self)
NSArray *data = [ParserForJSON parse:JSON];
if(data.count != 20) {
self.moreData = NO;
}
[self.data addObjectsFromArray:data];
[self.collectionView reloadData];
[self.refreshControl endRefreshing];
} error:^(NSError *error) {
}];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.data.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CustomData *data = [self.data objectAtIndex:indexPath.row];
CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
///.... some cell configuration
return cell;
}
然而,当我试图访问恰好为空的数据源时,cellForItemAtIndexPath
发生了随机崩溃。令人惊讶的是,当我在那时检查控制台时,数据源不是空的。所以我的猜测是有一些时间问题。我想对这种模棱两可的行为做一些深入的解释。
答案 0 :(得分:1)
当您调用refresh
方法时,会删除所有data
个对象,因此在调用cellForItemAtIndexPath
时,data
来源中没有数据。这就是致电id object = [data objectAtIndex:indexPath.row]
时返回nil
的原因。因此,请确保在requestToServerAtIndex
重新创建新数据之后再删除旧对象并更新UI。
编辑:
尝试删除[self.collectionView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
进行测试,此方法应调用cellForItemAtIndexPath