title: NSExpression based Core Data fetch does not retrieve current values (iOS 5, GCD)
body: <h2>What I am trying to do</h2>
  <p>I am using the code below to download data (historic foreign exchange rates) from my backend server (parse.com) to my app's Core Data store.</p>
  <p>The app checks for the latest available data stored locally and fetches only the newer data from the server. If there is no data stored locally yet, it fetches all data from the server.</p>
  <p>The way the code is set up, it fetches the data in batches of 100 objects, saves the objects in Core Data, gets the new latest date for which data is now locally stored (by using <code>NSExpression</code>) and fetches the next batch until no more new objects are left on the server (<code>objects.count = 0</code>).</p>
  <p>Because fetching is slow, I decided to run the fetching and Core Data saves on a back ground thread (using the new Core Data multi-treading model provided by iOS 5).</p>
  <p>Fetching from the backend server works fine, but...</p>
  <h2>My Problem</h2>
  <p>it seems that only those objects are evaluated by the <code>NSExpression</code> which are stored on disk (physically in the database) and not the objects which are still in memory and will be saved soon. Hence, the fetch retrieves mostly the &quot;old&quot; values from disk (memory).</p>
  <p>However, when using the following code of fetch (with no <code>NSExpression</code> and <code>NSDictionary</code> as result type), I get the current and correct values:</p>
  <pre><code>NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:localEntityName];
  NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@&quot;date&quot; ascending:YES];
  request.sortDescriptors = @[sortDescriptor];
  NSArray *results = [backgroundContext executeFetchRequest:request error:&amp;error];
  ForexHistory *forexHistoryItem = results.lastObject;
  NSDate *lastLocalDate = forexHistoryItem.date;
  NSLog(@&quot;last local date results: %@&quot;,lastLocalDate);
  </code></pre>
  <p>What's wrong with my code below, which uses <code>NSExpression</code> and dictionary as the fetch resultType ?</p>
  <h2>My question</h2>
  <p>How can I make sure that the <code>NSExpression</code> which looks for the latest locally available date returns the latest date?</p>
  <h2>The code</h2>
  <pre><code>- (void)seedForexHistoryInManagedObjectContext:(NSManagedObjectContext*)context {
    NSString* const localEntityName = @&quot;ForexHistory&quot;;
    NSString* const parseEntityName = localEntityName;
    NSString* const parseDateIdentifier = @&quot;date&quot;;
          
    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@&quot;date&quot;];
    NSExpression *maxPeriodExpression = [NSExpression expressionForFunction:@&quot;max:&quot;   
               arguments:@[keyPathExpression]];
          
    NSString *expressionName = @&quot;maxDate&quot;;
    NSExpressionDescription *expressionDescription  = [[NSExpressionDescription alloc] init];
    expressionDescription.name                      = expressionName;
    expressionDescription.expression                = maxPeriodExpression;
    expressionDescription.expressionResultType      = NSDateAttributeType;
          
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:localEntityName];
    request.propertiesToFetch = @[expressionDescription];
    request.resultType = NSDictionaryResultType;
      
    NSArray *currencies = @[@&quot;AUD&quot;,@&quot;EUR&quot;,@&quot;NZD&quot;,@&quot;GBP&quot;,@&quot;BRL&quot;,@&quot;CAD&quot;,@&quot;CNY&quot;];
      
    dispatch_queue_t downloadQueue;
    downloadQueue = dispatch_queue_create(&quot;download&quot;, NULL); // create serial dispatch queue
          
    NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    moc.parentContext = context;
    dispatch_async(downloadQueue,^{
       [moc performBlockAndWait:^{
            NSArray *objects;
               do {
                 NSError *error;
                 NSArray *dateResults = [moc executeFetchRequest:request error:&amp;error];
                 NSAssert(dateResults.count == 1,@&quot;Request error!&quot;);
                 NSDate *lastLocalDate = dateResults.lastObject[expressionName];
                 NSLog(@&quot;last local date results: %@&quot;,lastLocalDate);
                      
                 PFQuery *query = [PFQuery queryWithClassName:parseEntityName];
                 query.limit = 100;
                 [query orderByAscending:parseDateIdentifier];
                      
                 if (lastLocalDate) [query whereKey:parseDateIdentifier greaterThan:lastLocalDate]; // else query all
                      
                  objects = [query findObjects];
                  
                  [objects enumerateObjectsUsingBlock:^(PFObject *obj, NSUInteger idx, BOOL *stop) {
                          
                  ForexHistory *forexHistory = [NSEntityDescription    insertNewObjectForEntityForName:localEntityName
                                                                                     inManagedObjectContext:moc];
                          forexHistory.date = NULL_TO_NIL(obj[@&quot;date&quot;]);
                          
                          [currencies enumerateObjectsUsingBlock:^(NSString *currency, NSUInteger idx, BOOL *stop) {
                              [forexHistory setValue:NULL_TO_NIL(obj[currency]) forKey:currency.lowercaseString];
                          }];
                      }];
                      NSError *saveError = nil;
                      [moc save:&amp;saveError];
                      
                      if (!saveError) NSLog(@&quot;%lu forex rates saved successfully.&quot;,(unsigned long)objects.count);
                      else NSLog(@&quot;Error when downloading historic forex rates: %@&quot;,error.localizedDescription);
      
                 } while (objects.count &gt; 0);
            }];
  }
  </code></pre>
  <p>Thank you for your help!</p>