0

I have three arrays and I have copied all these arrays into a single array. All these three arrays are arrays of dictionaries.All arrays has a field called picture, but that pictures is coming from different sources- URL in one array, data in other and files in the third one.

Say, Array1 has dictionaries with a key - picture and its loaded from NSURL. Similarly, Array2 and Array3 has dictionaries with same key name - picture and loaded from ContentofFiles and NSData.

Now, I want to populate tableview, of course,m having Custom UITableViewCell, it has image view as its content view. To load that image, what should I do.

I was doing this thing..

NSURL *url  = [NSURL URLWithString:[[contactList objectAtIndex:indexPath.row] objectForKey:@"picture"]];
cell.contactImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

But, this will crash if cell.contactImageView.image don’t receive image from NSURL.So, what should I do? Any help, will be appreciated

But,

4

4 回答 4

3

您只需检查接收到的图像是否为空,如果是,则在未选择个人资料图片时设置一个名为 no photo 的模板照片图像,如 facebook 上的照片

    UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    if (img)
       cell.contactImageView.image = img;
    else
       cell.contactImageView.image = [UIImage imageNamed:@"no_photo.png"];
于 2012-06-07T06:49:41.627 回答
1

如果这些图像是从网上检索到的,我建议不要使用[NSData dataWithContentsOfURL:].

您应该使用异步加载图像的非阻塞方法。对表中的大量行使用此方法会导致性能问题。

这是我的建议,使用SDWebImage 库。易于使用,甚至更易于安装。

将库添加到项目后,下面就是#importUIImageView+WebCache.h使用示例。

 [cell.contactImageView.image setImageWithURL:[NSURL URLWithString:[[contactList objectAtIndex:indexPath.row] objectForKey:@"picture"]]
               placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
于 2012-06-07T07:12:38.863 回答
0

您可以在字典中再添加一个键,该键将指定从哪里拍照,因此如果您想提供来自不同来源的图像,您可以将图像提供给 cell.contactImageView。

于 2012-06-07T06:53:25.327 回答
0

非常感谢您的快速回复,尤其是@skram,由于您的建议,我的 tableview 性能提高了很多。我问过的问题,我想到的更好的答案是使用iskindofClass. 如果图像来自任何类,在某种条件下,我们可以检查该图像的来源并相应地填充我们的图像。

if ([[[contactList objectAtIndex:indexPath.row] objectForKey:@"picture"] isKindOfClass:[UIImage class]]) 
    {
        cell.contactImageView.image = [[contactList objectAtIndex:indexPath.row] objectForKey:@"picture"];
    }
    else if ([[[contactList objectAtIndex:indexPath.row] objectForKey:@"picture"] isKindOfClass:[NSString class]]) 
    {
        cell.contactImageView.image = [[contactList objectAtIndex:indexPath.row] objectForKey:@"picture"];
    }
    else if([[[contactList objectAtIndex:indexPath.row] objectForKey:@"picture"] isKindOfClass:[NSURL class]])
    {
        [cell.contactImageView setImageWithURL:[NSURL URLWithString:[[contactList objectAtIndex:indexPath.row] objectForKey:@"picture"]]placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    }

现在,我可以正确填充表格视图了。再次感谢scram.

于 2012-06-07T08:34:57.613 回答