0

我正在UITableView使用CustomCell. CustomCell包含UIImageView和 2 UILabel。在UIImageView我想从URL加载图像并且我想保存在我的文档目录中。

这是我尝试过的代码,

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:[URLarr objectAtIndex:indexPath.row]];//arr is NSMutablearray of image URL

UIImage *img1 = [UIImage imageWithContentsOfFile:savedImagePath];
if (!img1 || [UIImagePNGRepresentation(img1) length] <=0)
{
    id path =[URLarr objectAtIndex:indexPath.row];
    path = [path stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    NSURL *url = [NSURL URLWithString:path];
    NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:url, [NSString stringWithFormat:@"%d", indexPath.row+1], nil ];

    [self performSelectorInBackground:@selector(loadImageInBackground:) withObject:arr];

}

还有这个。

//—————————————-lazy loading———————–
- (void)loadImageInBackground:(NSArray *)urlAndTagReference
{
        NSData *imgData = [NSData dataWithContentsOfURL:[urlAndTagReference objectAtIndex:0]];
        UIImage *imgload = [[UIImage alloc] initWithData:imgData];

        NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:imgload, [urlAndTagReference objectAtIndex:1], nil];

        [self performSelectorOnMainThread:@selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];
}

- (void) assignImageToImageView:(NSArray *)imgAndTagReference
{
         NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
         NSString *documentsDirectory = [paths objectAtIndex:0];
         NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:[URLarr objectAtIndex:[[imgAndTagReference objectAtIndex:1] intValue]-1]];

         UIImage* imageToSave = savedImagePath;
         NSData *imageData = UIImagePNGRepresentation(imageToSave);
         [imageData writeToFile:savedImagePath atomically:NO];

}

崩溃原因显示NSInvalidArgumentException。图像也没有显示在UITableViewCell. 任何帮助,将不胜感激。

4

2 回答 2

0

对于表视图图像的延迟加载,可用的选项很少。可以在您的设计中使用它们以节省时间并避免重新发明轮子。
1.苹果懒加载代码——链接
2.SDWebImage——链接

干杯! 阿马尔。

于 2013-05-15T12:42:29.617 回答
0

我认为

NSData *imgData = [NSData dataWithContentsOfURL:[urlAndTagReference objectAtIndex:0]];

不管用。而是试试这个

UIImage *imgload = [UIImage imageWithData:[NSData dataWithContentsOfURL:[urlAndTagReference objectAtIndex:0]]]

这可能会有所帮助。现在试试这个。

UIImageView *imageView = [[UIImageView alloc]init];
[imageView_shake_image setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[urlAndTagReference objectAtIndex:0]]]];
UIImage *imgload = [imageView.image retain];

我不知道。试试看嘛

于 2013-05-15T12:54:29.557 回答