Lazy Loading UITableView Cell images in iPhone

L

.h
– (void) loadImageInBackground:(NSArray *)urlAndTagReference ;
– (void) assignImageToImageView:(UIImage *)img;

.m
– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:[disparrimgnm objectAtIndex:indexPath.row]];//disparrimgnm is NSMutablearray of imagename URL
UIImage *img1 = [UIImage imageWithContentsOfFile:savedImagePath];
if (!img1 || [UIImagePNGRepresentation(img1) length] <=0)
{
id path =[disparrimgnm objectAtIndex:indexPath.row];
path = [path stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSURL *url = [NSURL URLWithString:path];
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:url, [NSString stringWithFormat:@"%d", indexPath.row+1], nil ];

[self performSelectorInBackground:@selector(loadImageInBackground:) withObject:arr];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(18,40+(50*indexPath.row), 35, 35)];
imageView.tag = indexPath.row+1;
[tblSimpleTable addSubview:imageView]; //tblSimpleTable is uitableviw
}
}

//—————————————-lazy loading———————–
– (void) loadImageInBackground:(NSArray *)urlAndTagReference
{
NSData *imgData = [NSData dataWithContentsOfURL:[urlAndTagReference objectAtIndex:0]];
UIImage *imgload = [[UIImage alloc] initWithData:imgData];

NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:imgload, [urlAndTagReference objectAtIndex:1], nil];

[self performSelectorOnMainThread:@selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];
}

– (void) assignImageToImageView:(NSArray *)imgAndTagReference
{
for (UIImageView *checkView in [tblSimpleTable subviews] )
{
if ([checkView tag] == [[imgAndTagReference objectAtIndex:1] intValue])
{
[checkView setImage:[imgAndTagReference objectAtIndex:0]];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:[disparrimgnm objectAtIndex:[[imgAndTagReference objectAtIndex:1] intValue]-1]];
UIImage* imageToSave = [checkView image];
NSData *imageData = UIImagePNGRepresentation(imageToSave);
[imageData writeToFile:savedImagePath atomically:NO];
}
}
}

About the author

abdulgafar.nurbash
By abdulgafar.nurbash

Category