Efficient way to redraw a UITableViewCell when its data is available

I currently have one UITableViewController which contains many cells with simple data in it. When the UITableViewController instantiates a UITableViewCell, it starts to run a background thread for each individual cell to get its status from the server. UITableViewCell is a subclass and already has the UIImageView property, which must be added to the contentView as soon as the data from the server is ready.

My problem is that I need to call [tableView reloadData] every time I get new data from background threads. This is a bit overkill, since I can simply add a UIImageView to the contentView by accessing the affected cell directly. I just don’t know how best to find a cell when my data management utility is done doing its job (talking to the server).

Does it make sense to do something like passing the indexPath of the cell when calling my data manager to launch its background task and then passing that indexPath to the task? Is this too much?

What is your favorite way to handle this common task?

Thanks to the SO team.

+4
source share
2 answers

In the case when the data should change inside the cells, I do not use the identifier method dequeueReusableCellWithIdentifier: (NSString *). This prevents the caching of a UITableView cell. When the table view cells scroll from the screen, they are released. There is a delegate method,

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 

which is called immediately before your cell. You can use this, pass indexPath to the manager.

When your data returns, I usually call the method

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

to get the cell, then set the text in the cell and call its superclass method UIView, - (void)setNeedsLayout .
This will tell the cell to redraw.

Another way I did this is to use a custom cell, and this custom cell subclass calls the dispatcher for its data directly when drawing it. When the data is returned, it calls the delegate's own method to update its internal UILabel objects, and then calls setNeedsLayout.

+5
source

If you don't mind having a placeholder in your cell while the image is loading, you can use something like TTImageView in the Three20 Library. The image is always in the cell, and you specify its image URL. The image view processes the URL request, and when the image is loaded, it is automatically displayed.

While I am not using Three20, I am doing something very similar in my code. This is compatible with table cell reuse identifiers - when a cell scrolls from the screen, its image URL changes to a new value, which cancels the request for the URL (if it is still ongoing) and starts a new one. Combined with caching, scrolling the backup will load the image instantly.

0
source

All Articles