我正在将图像加载到我的UITableViewCell中,但它变得不稳定。我最多只有5-10个手机。
有什么简单的方法可以解决这个问题吗?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"appointmentCell";
AppointmentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *appointmentDictionaryTemp = [self.appointmentArray objectAtIndex:indexPath.row];
cell.patientNameLabel.text = [appointmentDictionaryTemp objectForKey:@"patient"];
cell.appointmentTimeLabel.text = [appointmentDictionaryTemp objectForKey:@"scheduled_time"];
NSString *urlString = [[appointmentDictionaryTemp objectForKey:@"patient_small_photo_url"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
UIImage * image = [UIImage imageWithData:imageData];
cell.patientImage.image = image;
return cell;
}发布于 2011-11-17 07:40:00
异步加载图像,并可能对其进行缓存。从阅读这个问题开始:Lazy load images in UITableViewCell
发布于 2011-11-17 07:41:57
dataWithContentsOfURL:是你的罪魁祸首。它在应用程序的主UI线程上执行同步(阻塞)网络请求,导致表视图在下载图像时锁定。
解决方案要复杂得多,它涉及到使用NSURLConnection (或其他一些第三方库)异步下载数据,从而允许UI在下载映像时保持响应。This是一个很好的参考资源。
发布于 2011-11-17 08:01:55
创建一个名为imageCache的ivar,它是一个NSArray。现在在init中运行这段代码
for (NSDictionary *appointmentDictionaryTemp in self.appointmentArray) {
NSString *urlString = [[appointmentDictionaryTemp objectForKey:@"patient_small_photo_url"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
UIImage * image = [UIImage imageWithData:imageData];
[imageCache addObject:image];
}现在在cellForRowAtIndexPath中
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"appointmentCell";
AppointmentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *appointmentDictionaryTemp = [self.appointmentArray objectAtIndex:indexPath.row];
cell.patientNameLabel.text = [appointmentDictionaryTemp objectForKey:@"patient"];
cell.appointmentTimeLabel.text = [appointmentDictionaryTemp objectForKey:@"scheduled_time"];
cell.patientImage.image = [imageCache objectAtIndex:indexPath.row];
return cell;
}https://stackoverflow.com/questions/8160223
复制相似问题