Monday, February 21, 2011

Displaying images from server in a table cell in a thread


We mostly use this concept when we need to load many images from server .Using this concept, the main Thread does not gets blocked till each image is loaded & user can interact with the UI. However, threading is used when you don't want your main thread to block till your aspected task is completed. 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

UIImageView *imgView= (UIImageView *)[cell.contentView viewWithTag:IMAGE_TAG];
id object = [imageDict objectForKey:[NSString stringWithFormat:@"%i,%i", indexPath.section, indexPath.row]];
if(!object){
[NSThread detachNewThreadSelector:@selector(displayingSmallImage:) toTarget:self withObject:indexPath];
}
else
{
if(![object isKindOfClass:[NSNull class]]){
UIImage *img = (UIImage *)object;
imgView.image = img;
}
}

}


imageDict is a global NSMutableDictionary


- (void) displayingSmallImage:(NSIndexPath *)indexPath{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *imageUrl = [url to be used for fetching image from the server];
imageUrl = [(NSString *)CFURLCreateStringByAddingPercentEscapes(nil, (CFStringRef)imageUrl, NULL, NULL, kCFStringEncodingUTF8)autorelease];
NSURL *url = [NSURL URLWithString:imageUrl];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

if(image){
[imageDict setObject:image forKey:[NSString stringWithFormat:@"%i,%i",indexPath.section,indexPath.row]];
}
else{
[imageDict setObject:[NSNull null] forKey:[NSString stringWithFormat:@"%i,%i",indexPath.section,indexPath.row]];
}

[self performSelectorOnMainThread:@selector(setImageInCell:) withObject:indexPath waitUntilDone:NO];
[pool release];

}


- (void)setImageInCell:(NSIndexPath *)indexPath{

[tableView_meals reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

No comments:

Post a Comment