title: CoreData - fetch objects by relationship in a batch for better performance
body: <h2>Introduction</h2>
  
  <p>Whenever possible, I'm trying to use find-or-create pattern in core data. When I'm doing this for a set of items that are identifiable by an id (doesn't matter if string or int), I do this in a batch (as oposed to do one fetch per item):</p>
  
  <pre><code>let itemIDs = Set(items.map { $0.id })
  let fetchRequest = NSFetchRequest&lt;E&gt;(entityName: E.entityName())
  fetchRequest.predicate = NSPredicate(format: "id IN %@", itemIDs)
  let foundObjects = try! context.fetch(fetchRequest)
  </code></pre>
  
  <h2>Problem</h2>
  
  <p>I have an entity that is not identifiable by an id but rather by its relationships to other entities</p>
  
  <pre><code>ItemPosition
  ===============
  attributes:
  - position
  ---------------
  relationships:
  - endpoint: N:1
  - item: N:1
  </code></pre>
  
  <p>The unique key here is combination of <code>endpoint</code> and <code>item</code>.</p>
  
  <p>For this entity, I do one fetch per item as I don't know how to do it in a batch:</p>
  
  <pre><code>var foundObjects: [ItemPosition] = []
  for item in items {
     let fetchRequest = NSFetchRequest&lt;E&gt;(entityName: E.entityName())
          fetchRequest.predicate = NSPredicate(format: "item = %@ AND endpoint = %@", item, endpoint)
     let results = try! context.fetch(fetchRequest)
     if let position = results.first {
         foundObjects.append(position)
     }
  }
  </code></pre>
  
  <p>This is not optimal as it hits SQL database for every item and I would like to avoid that.</p>
  
  <h2>Question</h2>
  
  <p>Is there a way how to fetch objects by multiple relationships in a batch? Something similar to <code>NSPredicate(format: "id IN %@", itemIDs)</code> metioned above?</p>