I'm new to Objective-C, so hopefully this all makes sense. I downloaded images from the server and displayed them as an image in the collectionView cellForItemAtIndexPath: method collectionView cellForItemAtIndexPath: The problem I am facing is that the images are not caching. It seems that every time the cell is reused, the linked image from the server is reloaded.
In my viewDidLoad method, I create an NSMutableDictionary:
imageDictionary = [[NSMutableDictionary alloc]initWithCapacity:50.0];
From reading the documentation and finding answers to such questions, I thought that this, as well as the following code, would be enough. I have been on this for a couple of days, and I know that there is something that I am missing, or a concept that I do not understand.
#pragma mark - UICollectionView Data Source - (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;{ NSLog(@"Begin retrieving photos"); return [self.photos count]; } -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return 1; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;{ CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath]; cell.imageView.image = nil; if (cell.imageView.image == nil) { dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL); dispatch_async(downloadQueue, ^{ NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[self.photos objectAtIndex:indexPath.row] objectForKey:@"fullimage"]]]; UIImage *image = [UIImage imageWithData:data]; [imageDictionary setObject:image forKey:@"Image"]; dispatch_async(dispatch_get_main_queue(), ^{ cell.imageView.image = [imageDictionary objectForKey:@"Image"]; [cell setNeedsDisplay]; }); }); } return cell; }
Any help would be greatly appreciated. Thanks in advance.
Brians
source share