Friday, May 24, 2013

Lazy loading example - image

Following image lazy loading example is collected from http://kindlybugs.com/tag/UITableView When using UITableViewController, loading all the images at the beginning is not recommended since it freezes the device for a time. AS a solution, there is another  method called lazy loading.

[Image lazy loading example]

AsyncImage.h

#import <UIKit/UIKit.h>


@interface AsyncImage : UIImageView {
NSURLConnection * connection;
NSMutableData * data;
}

- (void) loadImageFromURLString:(NSString *)theUrlString;

@end



AsyncImage.m


#import "AsyncImage.h"


@implementation AsyncImage

- (void)loadImageFromURLString:(NSString *)theUrlString {
[self.image release], self.image = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:theUrlString] 
cachePolicy:NSURLRequestReturnCacheDataElseLoad 
timeoutInterval:30.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(loadImageFromURLString:) withObject:nil waitUntilDone:NO];
return;
}
}

- (void)connection:(NSURLConnection *)theConnection 
didReceiveData:(NSData *)incrementalData 
{
    if (data == nil)
        data = [[NSMutableData alloc] initWithCapacity:2048];
    [data appendData:incrementalData];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection 
{
    self.image = [UIImage imageWithData:data];
    [data release], data = nil;
[connection release], connection = nil;
}

- (void)dealloc {
[data release];
[connection release];
    [super dealloc];
}


@end


--------------------------- Usage -----------------------


AsyncImage * _asyncImage = [[AsyncImage alloc] initWithFrame:UserFrame];
NSURL * imgURL = [NSURL URLWithString:ImagePath]; 
[_asyncImage loadImageFromURLString:[NSString stringWithFormat:@"%@",imgURL]];