objective-cfirebaseuiimageviewuiimagenscache

Store Image with NSCache from Firebase - Objective C


Hello everyone I'm trying to use NSCache to manage the images taken from Firebase via URL .. I'm using NSCache because every time I browse the tableview with the photos of my users the imageView continually recompense so I wanted to use NSCache to imagine the images for load only once and stored in the cache ... All this does not work but my images keep recharging continuously every time I browse the table view.

Can someone explain where I'm wrong? Thank you very much for any answer you can give me ...

My project is in Objective C

This is my code in custom Cell

@interface UserListMessageCell ()
@property (nonatomic, strong) NSURLSessionTask *task;
@property (nonatomic, strong) NSCache *imageCache;
@end

@implementation UserListMessageCell

-(void)loadImageUsingCacheWithURLString:(NSString *)urlString {

    UIImage *cachedImage = [_imageCache objectForKey:urlString];

    if (cachedImage) {
        _userPhoto.image = cachedImage;
        return;
    }


     _imageCache = NSCache.new

     NSURL *url = [NSURL URLWithString:urlString];
    [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [UIImage imageWithData:data];

            if (image) {
                self.imageCache = NSCache.new;
                [self.imageCache setObject:image forKey:urlString];
                self.userPhoto.image = image;
            }

            else self.userPhoto.image = [UIImage imageNamed:@"user"];
        });
    }] resume];
}

@end

This is my implementation in TableView

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UserListMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];

    UserReference *userRef = _isFiltered ? self.filteredUser[indexPath.row] : self.userArray[indexPath.row];

    cell.userNameLabel.text = userRef.name;
    cell.userUniversityLabel.text = userRef.university;
   [cell loadImageUsingCacheWithURLString:userRef.urlPhoto];

    return cell;
}

Solution

  • Seems the issue is that you are creating a new instance of NSCache in your loadImageUsingCacheWithURLString: method. When the cell is reused and a new image that is not cached is fetched you are creating a new NSCache which will keep just the last loaded image. Could you try instantiating the cache just in the cell's initializer and see if that works? Or maybe consider using a cache that's not a property of the cell to avoid loading same image in 2 different cells.