ios - Collection view images are flickering while scrolling -


im using following code populate collection view cells images.

- (uicollectionviewcell *)collectionview:(uicollectionview *)collectionview cellforitematindexpath:(nsindexpath *)indexpath {     static nsstring *identifier = @"cell";      uicollectionviewcell *cell = [collectionview dequeuereusablecellwithreuseidentifier:identifier forindexpath:indexpath];      uiimageview *recipeimageview = (uiimageview *)[cell viewwithtag:100];     recipeimageview.image = nil;     if ([imagearray count] >0){          dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_background, 0), ^(void) {             nsdata *data0 = [nsdata datawithcontentsofurl: [nsurl urlwithstring:[imagearray objectatindex:indexpath.row]]];             uiimage *image = [uiimage imagewithdata: data0];              dispatch_sync(dispatch_get_main_queue(), ^(void) {                 recipeimageview.image = image;             });         });      }      [spinnershow stopanimating];       return cell; } 

the problem that, when im scrolling images flickering , flashing. why so? how can make images stable without flickering?

just short overview, answer

uicollectionview highly optimized, , keep on-screen visible rows in memory. now, rows cells cached in pool , reused , not regenerated. whenever, user scrolls uicollectionview, adds just-hidden rows in pool , reuses them next visible rows.

so, now, coming answer

when scroll collectionview, collectionview datasource method gets called again every indexpath, coming in visible range , image gets downloaded again

- (uicollectionviewcell *)collectionview:(uicollectionview *)collectionview cellforitematindexpath:(nsindexpath *)indexpath 

solution

instantiate instance nsmutabledictionary, outside of method.

now in code

@implementation classname{   nsmutabledictionary *cachedimage; }  -(void)viewdidload(){   [super viewdidload];   cachedimage = [nsmutabledictionary new]; }  /*old code*/ uiimageview *recipeimageview = (uiimageview *)[cell viewwithtag:100];     recipeimageview.image = nil;      if ([imagearray count] >0){     //if image downloaded, use , don't download it.        if(cachedimage[[imagearray objectatindex:indexpath.row]] != nil){      recipeimageview.image = cachedimage[[imagearray objectatindex:indexpath.row]]; } else{  dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_background, 0), ^(void) {             nsdata *data0 = [nsdata datawithcontentsofurl: [nsurl urlwithstring:[imagearray objectatindex:indexpath.row]]];             uiimage *image = [uiimage imagewithdata: data0];              dispatch_sync(dispatch_get_main_queue(), ^(void) {                 recipeimageview.image = image;                 //****save downloaded image                  cachedimage[[imagearray objectatindex:indexpath.row]] = image; //****save downloaded image              });         }); }       }   /*old code*/