Reputation: 343
I am working on fetching an image from service into a table view cell. I have the image URL and i can fetch the image at cellForRowAtIndexPath
or in the layoutSubViews
method of table view cell. Which is the most efficient place to fetch remote data
The cellForRowAtIndexPath
method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "custom") as! MovieViewCell
cell.title = searchResultMovies[indexPath.row].title
cell.movieImage = searchResultMovies[indexPath.row].poster
return cell
}
The layoutSubViews
method
override func layoutSubviews() {
super.layoutSubviews()
if let title = self.title{
titleLabel.text = title
}
if let movieImage = self.movieImage {
movieImageView.loadImageFromString(imageString: movieImage)
}
}
if you notice the above code you can see i am calling loadImageFromString
from inside layoutsubviews
which could also be done at cellForRowAtIndexPath
. Which is the better place to do it and why?
Upvotes: 1
Views: 211
Reputation: 5073
Here's what the apple docs has to say about layoutSubviews:
Subclasses can override this method as needed to perform more precise layout of their subviews. You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want.
Since loading an image has nothing to do with autoresizing or adjusting constraints, you'd be misusing the method. Additionally, layoutSubviews is often times called more than once for a visible view (such as when you rotate the device). You don't need to load the image more than once.
cellForRowAt is the appropriate method for downloading the image you need to configure the cell.
Upvotes: 5
Reputation: 100503
There is no comparison between the 2 but the best practise is to make a config method inside the custom cell class and call it with the model to be set , layoutSubviews
is meant for usage when you need to do something that depend on bounds of the view , BTW also make sure that loadImageFromString
make use of a cache like SDWebImage
Upvotes: 2