Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6854895
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T01:41:25+00:00 2026-05-27T01:41:25+00:00

I’m trying to keep my UITableView scrolling smoothly while going through about 700 pictures

  • 0

I’m trying to keep my UITableView scrolling smoothly while going through about 700 pictures that are downloaded from the internet, cached (to internal storage) and displayed on each cell of the table. My code so far seems fine as far as scrolling performance. However, I noticed that sometimes, if the connection is being crappy or If I scroll really fast, a cell will display the wrong picture (that of another cell) for maybe about 1/2 a sec and then update to the image it is supposed to display.

I suspect 2 things so far:

A-
I might have a reentrancy issue from the point where my NSInvocationOperation calls back into the main thread with [self performSelectorOnMainThread:] to the point where the selector in the main thread gets executed. Though I don’t really spot any shared variables.

B-
Some sort of race between the main thread and the NSInvocationOperation? Like:

1 main thread calls cacheImageFromURL

2 inside this call, UIImage spans the worker thread

3 worker thread is almost done and gets to call performSelectorOnMainThread

4 the cell in question is dequeued to be reused at this point, so main thread calls cahceImageFromURL again for a new image.

5 inside this call, UIImage stops the NSOPerationQueue which causes the previous NSInvocationOperation thread to die.

6 BUT, the thread had already called performSelectorOnMainThread

7 so the selector gets excited causing the old image to load.

8 immediately after this, the recently spawned thread is done fetching the new image and calls performSelectorOnMainThread again, causing the update to the right image.

If this is the case, I guess I’d need to set a flag on entry to the cacheImageFromURL method so that the worker thread code doesn’t call performSelectorOnMainThread if there’s another thread (the main one) already inside cacheImageFromURL?

Here’s my code for my UIImageView subclass, which each cell in the table uses:

@implementation UIImageSmartView

//----------------------------------------------------------------------------------------------------------------------
@synthesize defaultNotFoundImagePath;
//----------------------------------------------------------------------------------------------------------------------
#pragma mark - init
//----------------------------------------------------------------------------------------------------------------------
- (void)dealloc
{ 
  if(!opQueue)
  {
    [opQueue cancelAllOperations];
    [opQueue release];
  }
  [super dealloc];
}
//----------------------------------------------------------------------------------------------------------------------
#pragma mark - functionality
//----------------------------------------------------------------------------------------------------------------------
- (bool)cacheImageFromURL:(NSString*)imageURL
{
  /*  If using for the first time, create the thread queue and keep it 
      around until the object goes out of scope*/
  if(!opQueue)
    opQueue = [[NSOperationQueue alloc] init];
  else
    [opQueue cancelAllOperations];

  NSString *imageName = [[imageURL pathComponents] lastObject];
  NSString* cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  NSString *cachedImagePath = [cachePath stringByAppendingPathComponent:imageName];

  /*  If the image is already cached, load it from the local cache dir.
      Else span a thread and go get it from the internets.*/
  if([[NSFileManager defaultManager] fileExistsAtPath:cachedImagePath])
    [self setImage:[UIImage imageWithContentsOfFile:cachedImagePath]];
  else
  {
    [self setImage:[UIImage imageWithContentsOfFile:self.defaultNotFoundImagePath]];
    NSMutableArray *payload = [NSMutableArray arrayWithObjects:imageURL, cachedImagePath, nil];

    /*  Dispatch thread*/
    concurrentOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadURI:) object:payload];
    [opQueue addOperation: concurrentOp];
    [concurrentOp release];
  }

  return YES;
}
//----------------------------------------------------------------------------------------------------------------------
/*  Thread code*/
-(void)loadURI:(id)package
{
  NSArray *payload = (NSArray*)package;
  NSString *imageURL = [payload objectAtIndex:0];  
  NSString *cachedImagePath = [payload objectAtIndex:2];

  /*  Try fetching the image from the internets.
      If we got it, write it to disk. If fail, set the path to the not found again.*/
  UIImage *newThumbnail = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];  
  if(!newThumbnail)
    cachedImagePath = defaultNotFoundImagePath;
  else  
    [UIImagePNGRepresentation(newThumbnail) writeToFile:cachedImagePath atomically:YES];

  /*  Call to the main thread - load the image from the cache directory
      at this point it'll be the recently downloaded one or the NOT FOUND one.*/
  [self performSelectorOnMainThread:@selector(updateImage:) withObject:cachedImagePath waitUntilDone:NO];
}
//----------------------------------------------------------------------------------------------------------------------
- (void)updateImage:(NSString*)cachedImagePath
{
  [self setImage:[UIImage imageWithContentsOfFile:cachedImagePath]];
}
//----------------------------------------------------------------------------------------------------------------------
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
  // Return YES for supported orientations
  return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

And the way this UIImage is used is in the context of cellForRowAtIndexPath, like so:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  UIImageSmartView *cachedImage;
  // and some other stuff...

  static NSString *CellIdentifier = @"Cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) 
  {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:CellIdentifier] autorelease];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleGray;

    // some labels and tags stuff..

    cachedImage = [[UIImageSmartView alloc] initWithFrame:CGRectMake(5, 5, 57, 80)];
    cachedImage.contentMode = UIViewContentModeCenter;
    cachedImage.defaultNotFoundImagePath = [[NSBundle mainBundle] pathForResource:@"DefaultNotFound" ofType:@"png"];
    cachedImage.tag = PHOTO_TAG;

    [cell.contentView addSubview:cachedImage];
    [cell.contentView addSubview:mainLabel];
    [cell.contentView addSubview:secondLabel];

  }
  else
  {
    cachedImage = (UIImageSmartView*)[cell.contentView viewWithTag:PHOTO_TAG];
    mainLabel = (UILabel*)[cell.contentView viewWithTag:MAINLABEL_TAG]; 
  }

  // Configure the cell...

  NSString *ImageName = [[[self.dbData objectAtIndex:indexPath.row] objectAtIndex:2] 
                         stringByReplacingOccurrencesOfString:@".jpg" 
                         withString:@"@57X80.png"];

  NSString *imageURL = [NSString stringWithFormat:@"www.aServerAddress.com/%@/thumbnail5780/%@", 
                        self.referencingTable, 
                        ImageName];

  [cachedImage cacheImageFromURL:imageURL];

  mainLabel.text = [[self.dbData objectAtIndex:indexPath.row] objectAtIndex:0]; 
  return cell;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T01:41:26+00:00Added an answer on May 27, 2026 at 1:41 am

    D33pN16h7 is right in that the problem was cell reuse. However, instead of trying to make the indexPath thread-safe through an NSURLConnection, I decided to reimplement the whole thing by moving the NSOperationQueue into the UITableViewController code and having the concurrent imageView class be actually a proper subclass of NSOperation (since I was using NSOperationInvocation in the first place to try and avoid the full-fledged NSOperation subclass).

    So now, the table controller manages it’s own NSOperationQueue, the operations are subclasses of NSOperation and I can cancel them from the table controller code as the table view scrolls past them. And everything works fast and nice.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm trying to create an if statement in PHP that prevents a single post
I am trying to loop through a bunch of documents I have to put
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.