Reputation: 1239
I made a chat application with like function.
It's an app that fetches every 10 seconds new messages data.
I would like to update the messages. I know it is enough to just overwrite the dataSource for the off-screen cells.
MessagesStore.shared.messages = newMessages
But what about the on-screen cells?
...
Is it efficient to use this code I wrote?
let visibleRowsIndexPaths = tableView.indexPathsForVisibleRows!
for indexPath in visibleRowsIndexPaths {
// Loading the new data (updated message, likes count)
let message = MessagesStore.shared.messages[indexPath.row]
if let cell = self.tableView.cellForRow(at: indexPath) as? MessageCell {
cell.messageLabel.text = message.message
cell.likesButton.setTitle("\(message.likes!) likes", for: .normal)
} else if let cell = self.tableView.cellForRow(at: indexPath) as? OwnMessageCell {
cell.messageLabel.text = message.message
cell.likesButton.setTitle("\(message.likes!) likes", for: .normal)
}
}
I could use tableView.reloadData()
as well, but it causes some bugs, like selection disappears sometime, tableView jumps, it is not smooth..
My code works fine and smooth, but is it efficient?
Upvotes: 0
Views: 1566
Reputation: 660
You can use self.tableView.reloadData()
in order to reload your entire table or self.tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: UITableViewRowAnimation.None)
in order to reload a specific cell.
You can read more about the UITableView class here
Upvotes: 0
Reputation: 793
You are doing the same in both code blocks. And in the worst case, you are asking your tableView two times for a cell - just because the class didn't match (but your needs are the same for both).
Interfaces (protocols in ObjC) let you define method signatures (and properties in Swift?). And that's what I'd do in ObjC: Define a protocol (interface in other languages) and simply require any cell for this tableView to implement it.
This attempt also eases further addition of other cells, which provide almost the same features.
Upvotes: 1