2016-03-02 74 views
0

我在與的CollectionView willDisplayCell叫了兩聲

-(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 。數據被重新加載,並且由於我處於底部單元格中,網絡請求再次發生,然後再次提取相同的數據。我如何防止它再次發出網絡請求?

+0

可能你能夠分享整個班級代碼??? –

+0

@muhammadRaheelMateen我已經添加了處理網絡請求 – Pablo

回答

0

之前迭代雖然所有響應的對象,只是檢查,以確保您的最後一個數據源對象不符合您的最後一個響應對象的venderIdvenderId(因爲在這種情況下,你已經檢索到的所有賣方)。這裏是僞代碼:

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

} 
+0

感謝您的回覆的代碼。我想要做的是當用戶滾動到最後一個單元格時拉出更多數據。目前我們的數據並不大,但在不久的將來會增長,所以隨着數據的增長,它將會提出多種請求。我想你已經用BOOL moreVendorsToRetrieve實現了。我的問題是當moreVendorsToRetrieve爲false/NO,並且最後一個單元格正在顯示,然後進行刷新調用以便重新填充數據源並調用reloaddata,並且由於最後一個單元格可見,將調用willdisplaycell中的方法。 – Pablo

+0

而且moreVendorsToRetrieve是一個錯字。它應該更多供應商可用。 – Pablo

+0

@Pablo我根據附加信息編輯了我的答案。 –