2015-02-10 66 views
1

我与tableview数据源和委托方法斗争。我有一个tableview,如果用户导航到该表视图控制器我调用Web服务方法,这是基于块的服务请求成功完成后重新加载tableview部分,但tableView:cellForRowAtIndexPath:indexPath调用两次。这是我的代码。UITableview委托和数据源调用两次

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值是在第一时间空。

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

对此有什么想法吗?非常感谢!

+0

你的'UITableView'的dataSource方法将在屏幕加载后被调用,如@Kex建议的,所以它第一次是'null',并且第二次重新加载它的数据将从你的内部触发异步块。 – Levi 2015-02-10 20:18:06

+0

尝试将reloadSections代码放在self.data = result [0]下方;不在调度块中。 – Kex 2015-02-10 20:20:39

+0

@Kex我试了一下。 – 2015-02-10 20:21:52

回答

3

你初始化了viewDidLoad中的数据数组吗?如果你没有,它会返回null。

如果你想避免两次调用实现代码如下尝试:

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

    if(!data) 
     return 0; 

    return yourNumberOfSections; 
} 
+0

对不起,数据不是数组。但无论如何,如果你没有初始化那个或结果数组,它将返回null。 – Kex 2015-02-10 20:16:06

+0

对不起。我知道。但它必须由api填充。 – 2015-02-10 20:16:40

0

这听起来像-tableView:cellForRowAtIndexPath:只是因为风景被被调用和表格试图您收到之前填充本身来自您的网络服务的任何数据。此时,您不会将self.data(无论那是什么)设置为任何有用的值,因此您可以改为null。当您的Web服务返回一些数据时,完成例程会导致相关部分重新加载,并且表格将绘制数据。

1

当它需要在屏幕上渲染单元格时,tableview调用cellForRowAtIndexPath。如果tableview在它有任何数据之前出现,self.data将是空的。

viewDidLoad设置[[self.data = NSMutableArray alloc] init](例如)和在UIITableViewdatasource/delegate方法应该正确返回numberOfRows等为零,直到您的Web服务填充数据。

相关问题