簡體   English   中英

UITableview委托和數據源調用兩次

[英]UITableview delegate and datasource called twice

我在使用tableview數據源和委托方法時遇到困難。 如果用戶導航到該表視圖控制器,我將獲得一個表視圖,我正在調用Web服務方法,該方法是在請求成功完成后成功重載了表視圖節,但又調用了兩次tableView:cellForRowAtIndexPath:indexPath的基於塊的服務。 這是我的代碼。

viewDidLoad

[[NetworkManager sharedInstance].webService getValues:self.currentId completion:^(NSArray *result, BOOL handleError, NSError *error) {

    self.data = result[0];

    dispatch_async(dispatch_get_main_queue(), ^{

        [self.tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 4)] withRowAnimation:UITableViewRowAnimationAutomatic];
    });

}

但是cellForRowAtIndexPath self.data值在第一次是null。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      NSLog(@"%@", self.data); // first time it print null 
}

那么對此有什么想法嗎? 非常感謝!

您是否在viewDidLoad中初始化了數據數組? 如果沒有,它將返回null。

如果要避免兩次調用tableview,請嘗試以下操作:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    if(!data)
        return 0;

    return yourNumberOfSections;
}

當需要在屏幕上呈現單元格時,tableview會調用cellForRowAtIndexPath 如果tableview在它具有任何數據之前出現,則self.data將為空。

例如,在viewDidLoad設置[[self.data = NSMutableArray alloc] init] ,在UIITableViewdatasource / delegate方法中,它應該正確地將numberOfRows等返回為零,直到您的Web服務填充數據為止。

聽起來像-tableView:cellForRowAtIndexPath:被調用只是因為加載了視圖,並且表在從Web服務接收任何數據之前試圖填充自身。 到那時,您將不會將self.data (無論是什么)設置為任何有用的值,因此將獲得null 當您的Web服務返回一些數據時,完成例程將導致重新加載相關部分,然后表將繪制數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM