0

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

- (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:在需要显示单元格之前,我会将下载/转换代码放在哪里,以便图像已经存储为图像?

谢谢,

杰克

4

1 回答 1

2

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

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

于 2011-05-28T16:50:49.723 回答