TableView Cell中的图像在滚动时会导致延迟

时间:2010-09-09 18:15:01

标签: iphone uitableview

我已将图像放入我的tableview单元格中,其中图像位于某个URL中。 我的问题是,当我的tableView已经显示数据时, 然后滚动查看桌面视图&在它对滚动做出反应之前需要一些时间或延迟..

我发现问题出在URL中的图像中,我还需要在tableview单元格中显示每个图像。  知道如何解决它吗?还是要优化?

这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

// Set up the cell
NSUInteger row = [indexPath row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

NSArray *arrLocal = [m_list objectAtIndex:row];
if ([arrLocal count] > 0) {
    cell.textLabel.text = [arrLocal objectAtIndex:2];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
    cell.detailTextLabel.text = [arrLocal objectAtIndex:3];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:12];

            //sample url of the image: http://www.mysite.com/images/DealExtreme/2657_1_small.jpg
    NSString *strTemp = [[NSString alloc] initWithString:@"http://www.mysite.com/"];
    NSString *urlString = [strTemp stringByAppendingString: [arrLocal objectAtIndex:1]];
    NSURL *url = [NSURL URLWithString:urlString];
    UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
    cell.imageView.image = image;       
    [strTemp release];
}

return cell;
 }

3 个答案:

答案 0 :(得分:0)

问题是你每次调用cellForRow时都在下载图像,我建议你在后台加载图像...一种方法是制作自定义单元格,让它们有方法或者某种方法排序将在后台加载图像然后设置它,另一种方法可能是在背景中加载所有图像并保持它们周围,然后设置单元格图像,这样每次单元格出现在屏幕上时你都不会重新加载图像...希望它有所帮助

答案 1 :(得分:0)

您必须异步加载该图像数据,否则您将阻止主线程。你当然希望避免这种情况。它会使您的应用无响应,如果延迟足够大,您的应用可能很容易被操作系统杀死。

因此,开始在后台下载图像(使用NSURLRequestNSURLConnection),并在数据完成时刷新单元格的内容。

答案 2 :(得分:0)

找到此链接http://www.markj.net/iphone-asynchronous-table-image/

回答我的问题。效果很好!谢谢markj! :)

相关问题