【发布时间】:2015-04-11 00:40:04
【问题描述】:
我在使用 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 的值在第一次为空。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"%@", self.data); // first time it print null
}
那么对此有什么想法吗?非常感谢!
【问题讨论】:
-
你的
UITableView的dataSource方法会按照@Kex的建议在屏幕加载后调用,所以第一次是null,第二次重新加载数据会从你的异步块内部触发。 -
尝试将 reloadSections 代码放在 self.data = result [0] 的下方;不在调度块中。
-
@Kex 我一直在尝试。
-
抱歉,要清楚一点,它是否打印任何值?它不会在第一个表调用时打印任何内容,但第二个调用是吗?
-
我现在明白了,如下所述,它被调用了两次。最初在加载时,然后在网络获取后的块中。这段代码没有任何问题。您是否希望 tableview 在您拥有数据或其他内容之前不初始化?
标签: ios objective-c delegates tableview datasource