繁体   English   中英

使用GCD在UITableviewCell中异步加载和缓存图像

[英]Loading and Caching Images Asynchronously in UITableviewCell using GCD

我正在使用json数据在UITableview显示图像并获取图像。 但是数据显示在UITablevewcells 但是不会显示图像。 显示图像需要时间和时间。 因此我想使用GCD异步显示uitableview的图像。但是我不知道异步GCD概念。请给我一个如何在编码中应用异步GCD概念的想法。 请给我任何指导。 这是我的代码。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{    
   [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
   NSError *err;
   NSString *strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
   NSLog(@"response is %@",strResponse);
   dit=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&err];
   NSArray *arrResults = [dit valueForKey:@"classifieds_mst"];
   listOfObjects = [NSMutableArray array];

for(dictRes in arrResults) {
 Attributes *at = [[Attributes alloc]init];      
at.classimage=[dictRes valueForKey:@"image_name"];
[listOfObjects addObject:at];
 }

[tableView reloadData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *identifier=@"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"identifier"];
     }
    classifiedimage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 80)];
    [cell.contentView addSubview:classifiedimage];
     NSString *str;
    str=att.classimage;
    if(str==nil) {
        classifiedimage.image=[UIImage imageNamed:@"image.png"];
    } else{
    url=@"My url";
     NSString *addurl=[url stringByAppendingString:str];
    classifiedimage.image = [UIImage imageNamed:addurl];
     }
return cell;
}

您可以尝试使用此方法,以便在cellForRowAtIndexPath方法中异步加载图像,这里我获取图像的URL并使用延迟加载。

dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(concurrentQueue, ^{

    dispatch_async(dispatch_get_main_queue(), ^{

        NSString *imageStr=[@"urlLink" stringByAppendingString:[populerPostImageArray objectAtIndex:indexPath.row]];

        [cell.myImgView setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"nopic.png"]];
    });
});

您可以使用惰性加载概念来加载图像。 为此,请参见下面的链接: https : //github.com/rs/SDWebImage

如果需要加载和缓存图像,可以使用APSmartStorage 它支持下载,内存和磁盘缓存,并会自动清除内存警告。 奇迹般有效:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM