我在视图顶部有一个自定义选项卡,用户可以来回切换两个视图。这两个视图都包含由来自服务器的数据动态填充的UICollectionView。根据我的理解,如果在调用[collectionView reloadData]时numberOfItemInSection返回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试图访问碰巧为空的数据源时,我得到了随机崩溃。令人惊讶的是,当我在控制台上检查时,数据源不是空的。所以我的大胆猜测是有一些时机问题。对于这种模棱两可的行为,我想得到一些深入的解释。
发布于 2015-08-24 08:42:19
当您调用refresh方法时,您将删除所有的data对象,因此当您的cellForItemAtIndexPath被调用时,data源中没有数据。这就是为什么当调用id object = [data objectAtIndex:indexPath.row]返回nil时。因此,确保在requestToServerAtIndex之后真实地创建新数据,然后删除旧对象并更新UI。
EDIT:尝试移除要测试的[self.collectionView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];,此方法应调用cellForItemAtIndexPath
https://stackoverflow.com/questions/32172720
复制相似问题