Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid slowdowns when scrolling table view?

I have custom table view cell with images (loaded from app document directory), labels, shadows etc. and when I scroll the table view it causes a lot of lags. How can I avoid these lags? I think it's possible to cache table view cell, or get a picture of the table view cell, but I don't know how to implement this. Please, help me :)

In cellForRowAtIndexPath: I set the data in if (cell == nil) block, but slowdowns are still there.

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        // ...configuring is here...
    }

    return cell;
}

P.S. Images in cell are high resolution, but reduced to fit...

like image 542
Randex Avatar asked Dec 12 '22 11:12

Randex


1 Answers

You should load your images in a background thread. If you're on iOS 4+, you can use GCD (Grand Central Dispatch) to load these asynchronously.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    static NSString *CellIdentifier = @"ImageCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier] autorelease];
    }
    NSString *imagepath = //get path to image here
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
        UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
        dispatch_sync(dispatch_get_main_queue(), ^{
            [[cell imageView] setImage:image];
            [cell setNeedsLayout];
        });
    });
    return cell;
}
like image 57
sudo rm -rf Avatar answered Dec 14 '22 23:12

sudo rm -rf