当数据源为空时,UITableView调用委托方法

时间:2014-11-11 14:19:26

标签: ios objective-c uitableview

我已将cellForRowAtIndexPath委托方法定义为:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PLOTCheckinTableViewCell *cell = (PLOTCheckinTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CheckinCellIdentifier forIndexPath:indexPath];
    if([self.items count] == 0){
        return cell;
    }
    NSDictionary *checkin = self.items[indexPath.row];
    // configure and return custom cell
}

我正在使用自定义单元格类(PLOTCheckinTableViewCell)。

我遇到了一个问题,用户会在第一个请求完成之前拉动刷新然后尝试再次拉取(在请求完成后,我重新加载表数据)。当他们这样做时,应用程序会崩溃并说indexPath.row基本上是不受限制的,即。数组是空的。

通过上面的IF检查,我减轻了崩溃。

然而,

  1. 为什么我的IF确实检查"工作",我认为在配置之前返回单元格没有视觉含义。这令人困惑

  2. 有没有更好的方法来防范这种情况发生(即表数据是否重新加载了一个空数组)?肯定numberOfRowsInSection会返回array count,这将是0? (如果它是一个空数组)

  3. 编辑(进一步代码)

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        float count = [self.items count];
        return count;
    }
    
    - (void)resetData {
        self.items = [NSMutableArray array];
    }
    
    -(void) refreshInvoked:(id)sender forState:(UIControlState)state {
        [self resetData];
        [self downloadHomeTimeline];
        [self.refreshControl endRefreshing];
    }
    
    - (void)downloadHomeTimeline {
        [self.apiClient homeTimeline:self.page completionBlock:^(NSDictionary *data){
            for (NSDictionary *obj in data[@"items"]) {
                [self.items addObject:obj];
            }
            [self.itemsTableView reloadData];
        }];
    }
    

1 个答案:

答案 0 :(得分:2)

我建议你做几件事。确保在主线程上执行[self.itemsTableView reloadData],并且我将[self.refresControl endRefreshing]放在完成块中。这样它就会在完成后停止刷新,你不应该让用户多次同时使用。

 - (void)downloadHomeTimeline {
        [self.apiClient homeTimeline:self.page completionBlock:^(NSDictionary *data){
            for (NSDictionary *obj in data[@"items"]) {
                [self.items addObject:obj];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.itemsTableView reloadData];
                [self.refreshControl endRefreshing];
             }); 

        }];
    }

同样在numberOfRowsInSection只返回计数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.items count];
}

添加答案。在接收新数据之前,不应重置阵列。在获取新数据时,用户仍然可以滚动表格,这意味着将创建新单元格,但您的NSMutableArray没有任何数据。那是当你得到错误和应用程序崩溃。您必须[tableView reloadData]清除表格,以便tableView知道有0行,我认为这不是您的意图。

让我知道这是否解决了这个问题。

相关问题