title: Download Images Asynchronously To NSData And Cache
body: <p>First of all, this is not a duplicate question. I have read many questions on Stack Overflow, but they didn't help to solve my problem completely.</p>
  
  <p>I am downloading images from a web service. As no one likes the UI to be stalled, I am using threads to download images separately. </p>
  
  <pre><code>NSURL *imageUrl = [NSURL URLWithString:storyImageURL];
  
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  
      thumbnailData = [NSData dataWithContentsOfURL:imageUrl];
  
      dispatch_async(dispatch_get_main_queue(), ^{
          thumbnail = [UIImage imageWithData:thumbnailData];
      });
  });
  </code></pre>
  
  <p>If I use the code exactly as above, the UI won't halt until it gets the data from the web service BUT the images are not cached.</p>
  
  <p>If I don't use threads, then the UI will stall, but the images are cached using the NSCoding methods (Archiving).</p>
  
  <p>My question is: What can I do to use threads and cache the thumbnails at the same time? Please do not suggest any third party libraries.</p>
  
  <p><strong>UPDATE:</strong> After going through the code again and again, there could be two problems that i can think of: </p>
  
  <p>1) Looks like NSKeyedArchiver and NSKeyedUnarchiver are being called before the thread is done downloading the images but thats just a guess. In a separate store file i am using NSKeyedArchiver and NSKeyedUnarchiver:</p>
  
  <pre><code>- (RSSChannel *)fetchRSSFeedWithCompletion:(void (^)(RSSChannel *, NSError *))block
  {
      NSURL *url = [NSURL URLWithString:@"http://techcrunch.com/feed"];
      NSURLRequest *req = [NSURLRequest requestWithURL:url];
  
      RSSChannel *channel = [[RSSChannel alloc] init];
      TheConnection *connection = [[TheConnection alloc] initWithRequest:req];
  
      //[connection setCompletionBlock:block];
  
      NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
      cachePath = [cachePath stringByAppendingPathComponent:@"HAHAHA.archive"];
  
      RSSChannel *cachedChannel = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePath];
  
      if (!cachedChannel) 
          cachedChannel = [[RSSChannel alloc] init];
  
      RSSChannel *channelCopy = [cachedChannel copy];
  
      [connection setCompletionBlock:^(RSSChannel *obj, NSError *err) {
          if (!err) {
  
              [channelCopy addItemsFromChannel:obj];
              [NSKeyedArchiver archiveRootObject:channelCopy toFile:cachePath];
          }
          block(channelCopy, err);
      }];
  
  
      [connection setXmlRootObject:channel];
      [connection start];
  
      return cachedChannel;
  }
  </code></pre>
  
  <p>2) Second problem that i can think of is that he UI is not refreshing after it tries to decode the thumbnail out of cache.</p>