Bangalore
Bangalore

Reputation: 1580

How to cache images in UITableView without external Libraries?

Iam trying to cache images without using external libraries in UITableview. But i didnt get any results for that. My images are loading from URL .i have more than 40 images and is there any way to cache rather than loading directly ??

am using following code for loading image form URL

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"cell";

    cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil)
    {
        cell = [[testingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:MyIdentifier]
        ;
    }


    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(concurrentQueue, ^{
        data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];

        dispatch_async(dispatch_get_main_queue(), ^{
            cell.img.image = [UIImage imageWithData:data];
        });
    });

    return cell;
}

Upvotes: 0

Views: 808

Answers (2)

Andrea
Andrea

Reputation: 26385

You can use NSCache, NSCache works like an NSMutableDictionary with the advantage that is thread safe, with also some auto removal policies
Depending on your requirements you can create a singleton instance of it:

@interface SharedCache : NSCache
+ (id)sharedInstance;

@end

@implementation SharedCache

- (void) emptyCache{
    [self removeAllObjects];
}


-(void) dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(id) init {
    self = [super init];
    if (self) {
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emptyCache) name:UIApplicationDidReceiveMemoryWarningNotification object:[UIApplication sharedApplication]];
    }
    return self;
}

+(id)sharedInstance
{
    static dispatch_once_t pred = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&pred, ^{
        _sharedObject = [[self alloc] init]; 
    });
    return _sharedObject;
}

@end

Of course you should take care about check whether or not the image is already cached with a specified key.

Upvotes: 1

SleepNot
SleepNot

Reputation: 3038

Why wouldn't you use libraries? A very good one to use is UIImageView+AFNetworking from AFNetworking UIKit which loads an Image from a URL asynchronously and also caches your images.

example code:

[yourImageView setImageWithURL:youURL placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Upvotes: 0

Related Questions