2014-03-25 96 views
0

我從UItableViewCell中的服務器加載圖像。在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; 
} 

有沒有什麼簡單的方法來做到這一點?

+0

你在哪裏分配你的手機? –

+0

爲什麼你要爲細胞使用10MB圖像?一個尺寸較小的圖像就足夠了,因爲它可能會被縮放(除非你的單元尺寸與圖像一樣大) – giorashc

+0

我爲'Cell'創建了一個'NSObject',並且我已經將它分配到'ViewDidLoad ' – iCoder

回答

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; 
    }); 
}); 
+0

'main_queue'圖像不會顯示在'UIImageViewCell' – iCoder

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你可以找到如何在高速緩存

添加圖片
0

請參考THIS教程。它描述了以有效的方式在UItableView中獲取/加載圖像。