内存在UITableviewcell中加载图像时出现问题?

时间:2014-03-25 12:09:38

标签: ios objective-c uitableview uiimage

我正在UItableViewCell中从服务器加载图像。

由于每个图像占用10MB大小会导致内存问题。 应用程序崩溃只要我滚动tableView

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    locationcellObject=[self.tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    NSDictionary *temp= [sortedArray objectAtIndex:indexPath.row];
    locationcellObject.title.text=[temp objectForKey:@"locationtitle"];
    locationcellObject.subtitle_Lbl.text=[temp objectForKey:@"category"];
    NSString *trimmedtitle = [[temp objectForKey:@"locationtitle"]stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *name=[NSString stringWithFormat:@"images/%@.png",trimmedtitle];
    NSString *imageName=[NSString stringWithFormat:@"http://my_URL_HERE/%@",name];
    _tempData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageName]];
    UIImage *display=[[UIImage alloc]initWithData:_tempData];
    locationcellObject.locationPic_img_View.image=display;
    locationcellObject.locationPic_img_View.contentMode=UIViewContentModeScaleAspectFit;

    return locationcellObject;
}

有没有简单的方法可以做到?

3 个答案:

答案 0 :(得分:0)

1)你应该在后台进行下载
2)制作图像的缩略图(尺寸较小的图像)

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^ {
_tempData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageName]];
UIImage *display=[[UIImage alloc]initWithData:_tempData];

//make a thumbnail of the image 

UIImage *display; 
CGSize destinationSize = ...;
UIGraphicsBeginImageContext(destinationSize);
[originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//
dispatch_async(dispatch_get_main_queue(), ^{
//put result to main thread
locationcellObject.locationPic_img_View.image= newImage;
     });
});

答案 1 :(得分:0)

在后台线程中下载图像,在块中下载图像。通过这种方式,两个线程将在您的应用程序主线程和后台线程中运行。它将减少主线程的负载。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    //Call your function or whatever work that needs to be done
    //Code in this part is run on a background thread

    dispatch_async(dispatch_get_main_queue(), ^(void) {

        //Stop your activity indicator or anything else with the GUI
        //Code here is run on the main thread

    });
}); 

还可以使用NSCache将下载的图像添加到缓存中,下次从缓存加载图像时

您可以在此处查看此link,您可以在此找到如何在缓存中添加图片

答案 2 :(得分:0)

请参阅THIS教程。它描述了以有效的方式在UItableView中获取/加载图像。