2014-10-03 96 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