2014-10-03 151 views
1

首先我用initWithCoder初始化表格,然后在单元格中加载数据。当数据源发生更改(这是Web服务)时,我想要重新加载表。只是为了测试我迷上了按钮动作,并添加了[self.tableView reloadData]TableView reloadData不重新加载?

但是表不重新载入但数据源已被更改。如果我转到不同的视图并返回表格视图,则会显示新数据。有什么建议么?

- (id)initWithCoder:(NSCoder *)aDecoder { 

    self = [super initWithCoder:aDecoder]; 
    if (self) { 
     self.titleList = [[SearchModel alloc] init]; 
     [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 
     [self.titleList load: ^(id json) { 
      [self.tableView reloadData]; 
      [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
     }]; 
    } 
    return self; 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    self.tableView.delegate = self; 
    self.tableView.dataSource = self; 

    static NSString *CellIdentifier = @"title"; 
    TitleDetailCell *cell = nil; 
    Model *title = nil; 

    title = [self.titleList get:indexPath.row]; 

    if (cell == NULL) 

    { 
     cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 


     [cell movieTitleLabel].text = [title get:@"title"]; 
     [[cell movieImageView] setImageWithURL: thumbnail]; 
    } 
    return cell; 
} 
+0

为什么你在cellForRowAtIndexPath方法中设置表代表和数据源?如果数据源没有设置在第一位,它将永远不会被调用 – Vladimir 2014-10-03 10:34:07

+0

我应该在哪里设置它?在重新加载数据之前,我曾尝试将它放在viewDidApper – 2014-10-03 10:59:31

+0

的任何位置。 viewDidLoad:是通常的地方。或者如果您使用IB - 最好在那里设置代理和数据源 – Vladimir 2014-10-03 11:19:39

回答

0

当时initWithCoder:称为tableView尚未建立。

移动代码initWithCoder:viewDidAppeare:,重新加载主线程中的数据,它应该帮助:

self.titleList = [[SearchModel alloc] init]; 
     [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 
     [self.titleList load: ^(id json) { 
      // Log data to see is data is ready 
      NSLog(@"%@",[title get:@"title"]); 
      // Reload table on the main thread 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       [self.tableView reloadData]; 
       [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
      }); 
     }]; 
+0

在这种情况下不会加载任何东西。我想在出现视图之前需要准备表格的数据。所以我把代码放在viewWillApper中,但没有重新加载。 – 2014-10-03 10:46:57

+0

是的,在调用reloadData之前需要准备好数据。将数据加载到viewDidAppeare中,记录数据以确保数据已准备就绪并重新加载表视图。如果日志显示您缺少SearchModel类中的问题数据。 – Greg 2014-10-03 11:10:54

+0

我把代码放在viewDidApper中,数据加载正常。但重新加载仍然无效。 – 2014-10-03 11:21:53

0

两件事情:

  1. 你不与到达数据做任何事在回调中(json)。你需要把它存储在任何地方,以便你可以在表格视图中显示?
  2. 回调发生在主线程还是后台线程?如果你正在做UI的东西,你需要确保它在主线程上
+0

数据存储在@property(nonatomic,strong)SearchModel * titleList; 你是什么意思的回调。数据源在它在模型类上更改的主线程上没有更改,该模型类是我从initWithCoder调用的那个。我知道数据何时更改,因此我正在调用重载表。 – 2014-10-03 10:53:19

+0

您的意思是模型将数据加载到它自己?通过回调,我的意思是你传递给'load:'的块。你似乎在评论中将类和线程混为一谈? – 2014-10-03 10:58:16

+0

不是。那是Model类的实例。 模型类从Web服务获取数据并返回数据。模型类在initWithCoder中调用。 我初学者可以请澄清你是什么意思的主线程,我应该怎么知道数据是否加载在主线程上。谢谢 – 2014-10-03 11:02:42

相关问题