Ios 如何停止在表视图中重复加载图像?
这是我的代码,显示来自服务器的图像。加载图像后,当您向下滚动然后返回时,图像将消失,并且在再次加载之前还有一个延迟Ios 如何停止在表视图中重复加载图像?,ios,objective-c,Ios,Objective C,这是我的代码,显示来自服务器的图像。加载图像后,当您向下滚动然后返回时,图像将消失,并且在再次加载之前还有一个延迟 dispatch_async(kBgQueue, ^{ NSString *profileImageStr = [[displayItems objectAtIndex:indexPath.row] objectForKey:@"image_url"]; NSURL* profileImgURL = [NSURL URLWithString:p
dispatch_async(kBgQueue, ^{
NSString *profileImageStr = [[displayItems objectAtIndex:indexPath.row] objectForKey:@"image_url"];
NSURL* profileImgURL = [NSURL URLWithString:profileImageStr];
NSData *profileImgData = [NSData dataWithContentsOfURL:profileImgURL];
NSString *postPhotoStr = [[displayItems objectAtIndex:indexPath.row] objectForKey:@"image_url"];
NSURL *postImgURL = [NSURL URLWithString:postPhotoStr];
NSData *postImageData = [NSData dataWithContentsOfURL:postImgURL];
dispatch_async(dispatch_get_main_queue(), ^{
if (postImageData && profileImgData != nil) {
cell.thumbnailImg.image = [UIImage imageWithData:profileImgData];
cell.bgImgView.image = [UIImage imageWithData:postImageData];
}else
{
cell.thumbnailImg.image = [UIImage imageNamed:@"noimage.jpg"];
cell.bgImgView.image = [UIImage imageNamed:@"noimage.jpg"];
}
});
}
);
return cell;
我认为您需要为映像实现缓存。将图像存储在
NSCache
中
//instance
NSCache *imageCache;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *simpleTableIdentifier=nil;
if([objRepresentative.team count]>0)
{
simpleTableIdentifier=[NSString stringWithFormat:@"%@",[objRepresentative.employeeID objectAtIndex:indexPath.row]];
}
else
simpleTableIdentifier = @"ContactTableCell";
ContactTableCell *cell = (ContactTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ContactTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
NSString *photoString=[NSString stringWithFormat:@"http://www.foo.com/%@",[searchPhoto objectAtIndex:indexPath.row]];
UIImage *image = [imageCache objectForKey:photoString];
if (image)
{
cell.ProfilePicture.image=image;
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:[photoString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:url]];
if(image)
{
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *small = [self imageWithImage:image scaledToSize:CGSizeMake(100, 100)];
cell.ProfilePicture.image=small;
});
[imageCache setObject:image forKey:photoString];
}
else
cell.ProfilePicture.image=[UIImage imageNamed:@"noPicture.png"];
});
}
}
return cell;
}
所有大写的句子都很难阅读。你需要在本地路径中存储图像,同时下载完成。这里是每次下载图片的地方。所以它会消失。请问我该怎么做?@user2838188请阅读此内容以了解如何存储文件:。您必须在下载文件后保存该文件,并检查设备中是否缓存了某些图像。如果是,则从设备加载,如果不是,则从internet加载。