Search code examples
iosuitableviewuisearchdisplaycontroller

Update a cell in a filtered table from background?


I have a table that displays images. It can be searched live, which adjusts the cells being displayed. The images are loaded in the background using a concurrent NSOperation subclass over the network when the image is not already immediately available.

After the image has been fetched, I want to update the table to display it.

How can I update the right cell?

  • I cannot rely on the cell that I have built in tableView:cellForRowAtIndexPath:, because the cell may have been repurposed for another row.
  • I cannot rely on the indexPath passed into tableView:cellForRowAtIndexPath:, because it may have changed since the update began due to a search term change.
  • I cannot search the visible cells in the table, because the cells themselves are instances of UITableViewCell and have no metadata.
  • I cannot search my filtered list, because I don't know what table to apply the changes to.

What am I missing?


Solution

  • The simplest solution is probably just to subclass UITableViewCell to add a tracking property. Something like this:

    @interface TrackingTableViewCell : UITableViewCell
    @property (strong) id trackingValue;
    @end;
    
    @implementation TrackingTableViewCell
    // Default @synthesize as of Xcode 4.4!
    @end
    

    When you set up the cell, set the trackingValue to the NSURL you are downloading the URL from. When you finish loading the image, check the trackingValue of the visible cells. If you find one that matches, great. If not, don't set it anywhere.

    You could theoretically do the same thing with the objc_setAssociatedObject() API, but I don't really see the value in doing that over just creating a simple subclass to track the value for you.