从网上下载图片是很慢的,为了不影响体验,选择延时加载图片是很好的办法。
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"myCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
Tweet *tempTweet = [tweets objectAtIndex:indexPath.row];
if (tempTweet.imgData == nil) {//没有头像
if (self.tableTweets.dragging == NO && self.tableTweets.decelerating == NO) {//不在拖动中和减速时,开始下载图片
ImgRecord *record = [[ImgRecord alloc] init];
record.url = tempTweet.img;
[self startIconDownload:record forIndexPath:indexPath];
}
cell.imageView.image = [UIImage imageNamed:@"avatar_loading.jpg"];//占位图片(等待下载)
}else{//已经存在图片
cell.imageView.image = tempTweet.imgData;
}
cell.textLabel.text = tempTweet.tweet;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ 于%@",tempTweet.author,tempTweet.fromNowOn];
return cell;
}
关键就是 [self startIconDownload:appRecord forIndexPath:indexPath];
- (void)startIconDownload:(AppRecord *)appRecord forIndexPath:(NSIndexPath *)indexPath
{
NSString *key = [NSStringstringWithFormat:@"%d",[indexPathrow]];
IconDownloader *iconDownloader = [imageDownloadsInProgressobjectForKey:indexPath];
if (iconDownloader ==nil)//已经在下载中的不用重复下载了,没有在下载中就往下走
{
iconDownloader = [[IconDownloader alloc] init];
iconDownloader.imgRecord = imgRecord;
iconDownloader.index = key;
iconDownloader.indexPathInTableView = indexPath;
iconDownloader.delegate = self;
[imageDownloadsInProgress setObject:iconDownloader forKey:key];//赋值
[iconDownloader startDownload];
[iconDownloader release];
}
}
IconDownloader 是一个下载图片封装类
- (void)appImageDidLoad:(NSString *)index//代理(重设图片
{
Tweet *t = [tweetsobjectAtIndex:[indexintValue]];
IconDownloader *iconDownloader = [imageDownloadsInProgressobjectForKey:index];//取值
if (iconDownloader != nil)//如果有头像
{
UITableViewCell *cell = [self.tableTweetscellForRowAtIndexPath:iconDownloader.indexPathInTableView];
cell.imageView.image = iconDownloader.imgRecord.img;
t.imgData = iconDownloader.imgRecord.img;//把图片赋到相应位置
}
}
- (void)startDownload
{
self.activeDownload = [NSMutableData data];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:appRecord.imageURLString]] delegate:self];
self.imageConnection = conn;
[conn release];
}