【问题标题】:app slowing down due to image load issue由于图像加载问题,应用程序变慢
【发布时间】:2013-03-14 10:59:01
【问题描述】:

我在应用程序中加载内容时遇到问题,我看到数据是由应用程序获取的,但图像需要很长时间才能加载,是否有可能在后文中加载图像。代码如下:

NSDictionary *dict=[discussionArray objectAtIndex:indexPath.row];
UIImageView *avatarimage = (UIImageView *)[cell viewWithTag:4];
NSString *photoStrn=[dict objectForKey:@"photo"];

 dispatch_async(dispatch_get_global_queue(0,0), ^{
                   NSString *u=[NSString stringWithFormat:@"http://%@",photoStrn];
                   NSURL *imageURL=[NSURL URLWithString:u];
                   NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
                   dispatch_sync(dispatch_get_main_queue(), ^{
                   UIImage *dpImage = [UIImage imageWithData:imageData];
                   if (dpImage==nil)
                   {
                     dpImage = [UIImage imageNamed:@"profileImage.png"];
                   }
                   avatarimage.image = dpImage;

        });

如果您需要更多详细信息,我会提供:)

【问题讨论】:

标签: ios objective-c uikit grand-central-dispatch


【解决方案1】:

您可以使用GCD 执行此操作:

dispatch_async(dispatch_get_global_queue(0,0), ^{
     for (NSDictionary *dic in discussionArray)
     {
        NSString *photoStr=[dic objectForKey:@"photo"];
        NSString * photoString=[NSString stringWithFormat:@"http://%@",photoStr];
        UIImage *dpImage =  [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:photoString]]];
        if (dpImage==nil)
        {
            dpImage = [UIImage imageNamed:@"profileImage.png"];
        }
     }
});

【讨论】:

  • 我尝试了这种方法,页面加载速度很快:),尽管滚动应用程序更改头像图像并重新加载图像存在一个问题。我想我犯了一些错误,我正在更新上面的代码。
  • @JamesMitchee 我猜你正在使用 tableView 并且在重用单元格时忘记将图像重置为默认值。
【解决方案2】:

获取SDWebImage Here 并将其添加到您的项目中并包含

UIImageView+WebCache.h

在类实现文件中

UIImageView *imag=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
[imag setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[[jsonarray objectAtIndex:indexPath.row]valueForKey:@"imgurl"]]] placeholderImage:[UIImage imageNamed:@"Icon@2x.png"]];
[self.view addSubview:imag];
[imag release];

SDWebImage 对于从 URL 加载图像会更有用。

希望对你有帮助!!!

【讨论】:

    【解决方案3】:

    詹姆斯,

    有了这条线,

    [NSData dataWithContentsOfURL:[NSURL URLWithString:photoString]]]
    

    您在主线程上进行同步网络调用。当前线程将挂起,直到网络调用完成。

    解决方案是进行异步网络调用。 AFNetworking 库提供了一个很好的异步加载图像的类别:UIImageView+AFNetworking

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多