首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >调用了UICollectionView cellForItemAtIndexPath,但数据源为空

调用了UICollectionView cellForItemAtIndexPath,但数据源为空
EN

Stack Overflow用户
提问于 2015-08-24 07:52:25
回答 1查看 929关注 0票数 0

我在视图顶部有一个自定义选项卡,用户可以来回切换两个视图。这两个视图都包含由来自服务器的数据动态填充的UICollectionView。根据我的理解,如果在调用[collectionView reloadData]numberOfItemInSection返回0,则不会调用cellForItemAtIndexPath。换句话说,如果正在调用cellForItemAtIndexPath,这意味着在源中有一些数据。下面是我在切换到一个视图到其他视图时使用的一些代码。

代码语言:javascript
运行
复制
- (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试图访问碰巧为空的数据源时,我得到了随机崩溃。令人惊讶的是,当我在控制台上检查时,数据源不是空的。所以我的大胆猜测是有一些时机问题。对于这种模棱两可的行为,我想得到一些深入的解释。

EN

回答 1

Stack Overflow用户

发布于 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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32172720

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档