Introduction
Whenever possible, I try to use a search or create pattern in the master data. When I do this for a set of elements that are identified by an identifier (it does not matter if a string or int), I do this in a package (since this is excluded for one selection for each element):
let itemIDs = Set(items.map { $0.id }) let fetchRequest = NSFetchRequest<E>(entityName: E.entityName()) fetchRequest.predicate = NSPredicate(format: "id IN %@", itemIDs) let foundObjects = try! context.fetch(fetchRequest)
Problem
I have an object that is not identified by an identifier, but rather by its relationship with other objects
ItemPosition =============== attributes: - position --------------- relationships: - endpoint: N:1 - item: N:1
The only key here is the combination of endpoint and item .
For this object, I make one choice for each element, since I do not know how to do this in the package:
var foundObjects: [ItemPosition] = [] for item in items { let fetchRequest = NSFetchRequest<E>(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) } }
This is not optimal, since it gets into the SQL database for each element, and I would like to avoid this.
Question
Is there a way to retrieve objects with multiple relationships in a package? Something similar to NSPredicate(format: "id IN %@", itemIDs) metioned above?
source share