我正在使用Twitter API创建一个应用程序并使用JSON进行解析,每次我将图像加载到单元格中时,它会拍摄多个图像,而且一切都运行缓慢。我将如何获取图像,然后将相同的图像放入所有单元格中。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"TweetCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *text = [tweet objectForKey:@"text"];
NSString *time = [tweet objectForKey:@"created_at"];
time = [time stringByReplacingOccurrencesOfString:@" +0000 "withString:@"/"];
NSString *twitterImage = [[tweet objectForKey:@"user"] objectForKey:@"profile_image_url_https"];
NSString *completeImage = [NSString stringWithFormat:@"%@", twitterImage];
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: completeImage]];
imageLabel.image = [UIImage imageWithData: imageData];
cell.imageView.image = [UIImage imageWithData: imageData];
cell.textLabel.text = text;
cell.textLabel.numberOfLines = 3;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", time];
}
return cell;
}
现在看起来像这样,但滚动时真的很迟钝。 http://gyazo.com/8ab8325f3921fdb7e4f0ea0107d389ac.png
答案 0 :(得分:1)
在我看来问题就在这些方面:
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *twitterImage = [[tweet objectForKey:@"user"] objectForKey:@"profile_image_url_https"];
我相信这是为每个细胞获取图像的新副本。每个indexPath.row都是一条新推文,因此您将获得多个twitterImage
答案 1 :(得分:0)
如果它始终是相同的图片,请在表的加载之前在类参数中加载它(例如在viewDidLoad
中),并始终使用此参数。
如果是动态的,请使用performSelectorInBackground
在后台加载图片。
答案 2 :(得分:0)
您应该使用缓存来存储图像。我希望这个链接可以帮助你:
http://khanlou.com/2012/08/asynchronous-downloaded-images-with-caching/
答案 3 :(得分:0)
您遇到的问题是因为您正在下载主线程上的所有图像。
要解决这个问题:
使用NSOperationQueue使用单独的线程下载图像。 一个很好的教程:http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues
使用此类'AsyncImageView'。我用过这个,它运行正常。因此,您需要使用AsyncImageView类,而不是UIImageView,这个库将异步管理您的下载。
https://github.com/nicklockwood/AsyncImageView