views:

3394

answers:

4

Hi

I have some 50 custom cells in my UITableView. I want to display an
image and a label in the cells where I get the images from URLs.

I want to do a lazy load of images so the UI does not freeze up while
the images are being loaded. I tried getting the images in separate
threads but I have to load each image every time a cell becomes
visible again (Otherwise reuse of cells shows old images) Can someone please tell
me how to duplicate this behavior.

Any other suggestions are welcome

Thanks.

A: 

I am not aware of any built in way to accomplish this but it sounds like you have something working with another thread already.

Assuming that your only remaining problem now is invalidating the contents of a cell when it comes back into view you should look at:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

By implementing this delegate method you could check the contents of the cell before it draws to see if it needs new contents. If it does then you could empty the cells contents and trigger your threaded loading again.

You might also consider posting some code.

Jon Steinmetz
+6  A: 

There's a vey good official example here from Apple : http://developer.apple.com/iphone/library/samplecode/LazyTableImages/index.html I think you'll find the right approach in there....

yonel
A: 

I have caught one bug in the lazy loading example , That if I push tableview to another view and conme back repeatedly if i do I got objmsg error

the delegate method in the Icondownloader caught an error please help me in this

crystal
+1  A: 

I'd suggest going for an NSOperation and doing whatever you need on another thread.

This is a class I wrote for image loading:

- (id)initWithTarget:(id)trgt selector:(SEL)sel withImgURL:(NSString *)url {
    if(self = [super init]) {
     if(url == nil || [url isEqualToString:@""])
      return nil;
     target = trgt;
     action = sel;
     imgURL = [[NSURL alloc] initWithString: url];
    }
    return self;
}

- (void)main {
    [NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil];
}

- (void)loadImage {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    UIImage *img = [UIImage imageNamed: @"default_user.png"];
    if(![[imgURL absoluteString] isEqualToString: @"0"]) {
     NSData *imgData = [NSData dataWithContentsOfURL: imgURL];
     img = [UIImage imageWithData: imgData];
    }
    if([target respondsToSelector: action])
     [target performSelectorOnMainThread: action withObject: img waitUntilDone: YES];
    [pool release];
}

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

Hope that helps!

~ Natanavra.

natanavra