来自URL(RSS阅读器)的图像显示在表格视图中 - 问题

时间:2011-05-28 16:38:38

标签: objective-c xml ios uitableview custom-cell

我遇到了表视图和一些自定义单元格的问题。这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"cellForRowAtIndexPath");
static NSString *MyIdentifier = @"customCell";

EventTableCell *cell = (EventTableCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];

if (cell == nil) {
    //cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    [[NSBundle mainBundle] loadNibNamed:@"EventTableCell" owner:self options:nil];
    cell = self.eventCell;
}

//Set up the cell
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
[[cell eventNameLabel] setText:[[stories objectAtIndex: storyIndex] objectForKey: @"title"]];
[[cell eventDateLabel] setText:[[stories objectAtIndex: storyIndex] objectForKey: @"date"]];

NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: @"link"];

// clean up the link - get rid of spaces, returns, and tabs...
storyLink = [storyLink stringByReplacingOccurrencesOfString:@" " withString:@""];
storyLink = [storyLink stringByReplacingOccurrencesOfString:@"\n" withString:@""];
storyLink = [storyLink stringByReplacingOccurrencesOfString:@"  " withString:@""];

//NSString *string = [[NSString alloc] stringWithString:[[stories objectAtIndex: storyIndex] objectForKey: @"link"]];
NSURL *url = [NSURL URLWithString:storyLink];
NSData *data = [[NSData alloc] initWithContentsOfURL: url];
UIImage *image = [UIImage imageWithData: data];
[[cell eventImage] setImage:image];

return cell;
}

我的桌子中有很多这些自定义单元格,超过了视图可以立即显示的单元格。因此,我需要向上/向下滚动以查看所有单元格。我的问题是,当我滚动它很多时,在调试器控制台中,当每个新单元进入视图时,它调用cellForRowAtIndexPath。每个单元格都保存一个从URL下载的图像,因此必须转换为UIImage。我相信这是造成滞后的原因。

任何人都可以指导我下载图像并将其显示在单元格中而不会导致应用程序出现严重延迟吗?

IE:我会在哪里下载/转换代码,以便在需要调度单元格之前将图像存储为图像?

谢谢,

杰克

1 个答案:

答案 0 :(得分:2)

如果您想预先下载图像,可以在应用程序的任何位置执行此操作并将其缓存以供日后使用。例如,您可以在下载并解析RSS源后立即开始下载。您可以将它们保存在[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]返回的目录中。最好使用异步方法下载它们,并且一次只能激活一些下载以获得最佳性能。

如果要根据需要加载它们,请在分配单元格时设置占位符图像,并使用异步NSURLConnection等进行下载。下载完成后,将占位符替换为真实图像(当然,将其缓存以便稍后重复使用)。