UITableView中的延迟加载崩溃应用程序

时间:2013-05-15 12:31:38

标签: ios objective-c uitableview lazy-loading

我正在使用UITableView CustomCellCustomCell包含UIImageView和2 UILabel。 在UIImageView我想从网址加载图片,我想保存在我的文档目录中。

这是我尝试过的代码,

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中。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

对于延迟加载表格视图图像,可用的选项很少。可以在您的设计中使用它们以节省时间并避免重新发明轮子的努力 1. Apple延迟加载代码 - link
2。 SDWebImage - link

干杯! 阿玛尔。

答案 1 :(得分: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];

我不确定。试试吧