簡體   English   中英

每當對應於該單元格的NSFetchedResultsController中的對象發生更改時,如何使單元格的外觀更新?

[英]How do I make what my cell looks like update each time there is a change to the object in NSFetchedResultsController that corresponds to the cell?

我在我的應用程序中使用Core Data,並在其中使用NSFetchedResultsController在表視圖中使用它。 我可以對單元格/數據執行各種操作,例如向左或向右滑動以分別刪除或標記該單元格為已讀(這也會刪除數據)。

在我說的情況下,將單元格標記為已讀(這還將相應的Core Data對象的isRead屬性設置為YES ),我希望該單元格進行可視更新以指示這一點。 視覺更新使單元格看起來更亮(例如已讀郵件與未讀電子郵件的外觀)。

我怎么發生的? (即,當對應於其的對象具有屬性更改時更新單元格。)

我在NSFetchedResultsController此委托方法中嘗試過:

- (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:
            [self configureCell:(ArticleCell *)[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;

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

然后選擇NSFetchedResultsChangeUpdate ,然后調用configureCell: NSFetchedResultsChangeUpdate如下所示:

- (void)configureCell:(ArticleCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    Article *article = [self.fetchedResultsController objectAtIndexPath:indexPath];

    cell.article = article;
}

它調用了我的UITableViewCell子類, ArticleCell的自定義article屬性設置器。 在這種方法中,我基本上從以下內容開始:

- (void)setArticle:(Article *)article {
    if (_article != article) {

將要設置為該單元格的現有文章與新文章進行比較(因此,只有在發生更改的情況下它才會更新)。 但是,此if語句中的代碼永遠不會被調用! 它跳過去並存在該方法。 在該if語句中,我具有所有自定義代碼,可以根據該文章的屬性( isReadkind等)來設置單元格的外觀

我應該如何處理呢? 我只希望每當對應於該單元格的對象有更新時,該單元格就會反映該更新。 改變讀取狀態,還是其他。

在if語句中,您正在將兩個引用與同一個對象進行比較,因此,當從NSFetchedResultsChangeUpdate類型的更改中調用設置方法時,它將始終為true。

您實際上並不需要if,只需信任controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:方法中的代碼,並在該方法請求時始終更新該單元格即可。

因為文章對象是相同的,所以它不會進入內部。 但是,其屬性可能會更新。

您可能需要更改if或引入其他方法,例如-[ArticleCell update] ,該方法檢查是否會影響單元格外觀的任何屬性被更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM