CollectionView willDisplayCell调用了两次

时间:2016-03-02 19:40:07

标签: ios objective-c uicollectionview

我遇到了

的问题
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{}

我使用此方法确定将显示最后一个单元格,然后发出网络请求以提取更多数据。这工作正常,直到我从最后一行再次发出请求(当我的一个BOOLS为假时),例如:

    -(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
       if (indexPath.item = [self.collectionView.datasource count]-1 && self.moreVendorsAvaiable) {
      [network request:^(id response,id error){
      if (!error){
      [self processResponse:response];
       }                

        }];
     }
 }

- (void) parseMoreVendors:(id)response{
//If response is > 0, there are more vendors to retrieve
NSLog(@"response");
if ([response count]>0) {
    id parsedObject = nil;
    NSMutableArray *vendorsArray = [NSMutableArray arrayWithArray:self.datasource.content[@"rows"];
    NSMutableArray *updates = [[NSMutableArray alloc]init];
    FeaturedHeader *header = self.datasource.content[@"header"];
    Vendor *firstFeatured = header.firstFeatured;
    Vendor *secondFeatured = header.secondFeatured;

    for (id object in response) {
        //check if the response object is a featured vendor and return if it is
        if ( [firstFeatured.vendorId isEqual:object[@"id"]] || [secondFeatured.vendorId isEqual:object[@"id"]] ){
            self.featuredReturned = YES;
            return;
        }
        parsedObject = [[Vendor alloc] initWithDictionary:object];
        [updates addObject:parsedObject];
    }

    [vendorsArray addObjectsFromArray:updates];

    NSDictionary *content = [[NSDictionary alloc] initWithObjectsAndKeys:header, @"header", vendorsArray, @"rows", nil];

    [self.datasource setContent:content];
    [self.collectionView reloadData];
}else{
    self.moreVendorsAvailable = NO;
}

}

当检索数据并更新数据源时,我调用collectionView reloadData。数据被重新加载,因为我在底部单元格中再次进行网络请求,然后再次提取相同的数据。如何防止它再次发出网络请求?

1 个答案:

答案 0 :(得分:0)

Before iterating though all of your response objects, just check to make sure the venderId of your last dataSource object doesn't match the venderId of your last response object (since in that case you would have already retrieved all of the Vendors). Here is the pseudocode:

if (lastDataSource.venderId isEqual:object[@"id"])
{
  moreVendorsAvailable = NO;
  return;

}