What is the most efficient way to ensure content in cell are not re-used incorrectly
I am trying to add youtube videos to my UITableView via the following code. The trouble I had was the fact that the cell was being reused and the UIWebviews were also being reused causing the wrong videos to appear in the wrong cells.
I tried to resolve this issue by explicitly removing the UIWebview from superview before I set the video and also if the cell does not contain a youtube video.
But this seems rather expensive and inefficient. Can anyone advise me on a more efficient way of doing this so that the webview (containing the video) does not get reused in the wrong cells?
Code snippet from "cellforRowAtIndexPath":
//Re-create a UIWebview for youtube video everytime the cell is loaded
UIWebView *thisYouTubeVideo = [[UIWebView alloc]init];
//Check if this cell contains a youtube video
if (self.youtube_url !=nil)
{
//This is the first time I explicitly remove the UIWebview from cell's contentview
for (UIView *subview in [self.contentView subviews]) {
if ([subview isKindOfClass:[UIWebView class]]) {
[subview removeFromSuperview];
}
}
//This is just to set the frame of the UIWebview
thisYouTubeVideo.frame = CGRectMake(CELL_TEXT_LEFT_MARGIN, currentYAxisValue, 240, 240);
//Key for caching
NSString *videokey=[NSString stringWithFormat:@"%@",self.answerForCell.youtube_url];
//Check if webview has been created before, just load it from the dictionary (cache)
if([self.youtubeVideoCache objectForKey:videokey]) {
thisYouTubeVideo = [[self.youtubeVideoCache objectForKey:videokey]reta开发者_运维知识库in];
}
else
{
//If webview does not exist in cache, load the url to webview and store in cache
NSString * videoHTML = [self embedYouTube:self.answerForCell.youtube_url frame:CGRectMake(CELL_TEXT_LEFT_MARGIN, currentYAxisValue, 240, 240)];
[thisYouTubeVideo loadHTMLString:videoHTML baseURL:nil];
[self.youtubeVideoCache setObject:thisYouTubeVideo forKey:videokey]; //Save webview in dictionary
}
//add the uiwebview to the cell's content view
[self.contentView addSubview:thisYouTubeVideo];
[thisYouTubeVideo release];
}
else
{
//If the cell DOES not contain a youtube video, do the following
thisYouTubeVideo.frame = CGRectZero;
//This is the second time I am explicitly removing the webview from cell's content view
for (UIView *subview in [self.contentView subviews]) {
if ([subview isKindOfClass:[UIWebView class]]) {
[subview removeFromSuperview];
}
}
}
Use your videoKey as the cell identifier
[tableView dequeueReusableCellWithIdentifier:videoKey]
,
but keep in mind that this will impact on memory usage, because you do not reuse the allocated cells any more.
精彩评论