title: Core Data: fetching items is slow with predicate
body: <p>For my iPhone application I set up a data model for Core Data. It contains one entity <code>Words</code> and its attributes are <code>language : String</code>, <code>length : Integer16</code> and <code>word : String</code>.</p>
  
  <p>I prefilled my model's SQLite database with a word list (200k items) writing a separate iPhone application using the identical data model and coping the filled database to the main application.</p>
  
  <p>Now using NSFetchedRequest I can query for managed objects as I like, but the results come in slow. I use the following method:</p>
  
  <pre><code>- (NSString *)getRandomWordLengthMin:(int)minLength max:(int)maxLength
  {
      NSString *word = @"";
  
      MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
      NSManagedObjectContext *context = [appDelegate managedObjectContext];    
      NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
      NSEntityDescription *entity = [NSEntityDescription entityForName:@"Words"
                                                inManagedObjectContext:context];
      [fetchRequest setEntity:entity];
  
      NSString *predicateString = @"length &gt;= %d AND length &lt;= %d";
      NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString,
                                minLength, maxLength];
      [fetchRequest setPredicate:predicate];
  
      NSError *error = nil;
      int entityCount = [context countForFetchRequest:fetchRequest error:&amp;error];
      [fetchRequest setFetchLimit:1];
      if(entityCount != 0)
      {
          [fetchRequest setFetchOffset:arc4random()%entityCount];
      }
  
      NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&amp;error];
      if([fetchedObjects count] != 0)
      {
          Words * test = [fetchedObjects objectAtIndex:0];
          word = [NSString stringWithFormat:@"%@", [test word]];
      }
  
      return word;
  }
  </code></pre>
  
  <p>Using an SQLite editor I already set an index manually on column zLength, but this didn't bring any speedup. Where is the bottleneck?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I figured out that getting <code>int entityCount = ...</code> is slow. But even getting all objects and then selecting one random word is slow:</p>
  
  <pre><code>Words * test = [fetchedObjects objectAtIndex:arc4random()%[fetchedObjects count]];
  </code></pre>