2013-02-25 28 views
0

我想根據文檔目錄中是否存在文件來更改UITableViewCell。我覺得這應該是基於通知,並且當對象isAvailable屬性發生變化時應該發送通知。基於定製核心數據設置器發送NSN通知

我不想意外地創建線程問題。由於我正在主線程上操作核心數據對象,因此在我的具體類上設置自定義設置器以發佈通知時應該可以嗎?

這樣做的最好方法是什麼?我應該創建自己的通知,還是應該鎖定核心數據已發佈的內容?

回答

1

這很簡單,如果你使用NSFetchedResultsController。該類可與UITableView結合使用,以減少內存開銷並縮短響應時間。

你可以在NSFetchedResultsController Class ReferenceNSFetchedResultsControllerDelegate Protocol Reference找到文檔。

此外,您可以實施NSFetchedResultsController的委託方法。通過實施NSFetchedResultsController委派方法,它允許您監聽數據(您註冊的NSManagedObjectContext)中的操作,例如添加,移除,移動或更新,因此也可以在您的表中進行操作。

關於這個問題的一個很好的教程是core-data-tutorial-how-to-use-nsfetchedresultscontroller。在這裏你可以找到所有的元素來建立一個UITableView,一個NSFetchedResultsController及其代表。

說了這個,關於你的問題,你可以使用這種技術來改變的內容,當isAvailable屬性(特定的NSManagedObject)改變。特別是,您應該實施以下委託方法來響應特定更改(請參閱評論)。

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { 

    UITableView *tableView = self.tableView; 

    switch(type) { 

     case NSFetchedResultsChangeInsert: 
      [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeDelete: 
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeUpdate: // <---- here you will change the content of the cell based on isAvailable property 
      [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; 
      break; 

     case NSFetchedResultsChangeMove: 
      [tableView deleteRowsAtIndexPaths:[NSArray 
arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      [tableView insertRowsAtIndexPaths:[NSArray 
arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
    } 
} 

希望它有幫助。

+0

哇,謝謝!這非常有幫助。我將立即開始實施! – Weston 2013-02-26 13:10:04

+0

@Kronusdark不客氣。乾杯。 – 2013-02-26 13:37:12