CoreData - select objects by relationship in a package for better performance

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?

+5
source share
1 answer

I can come up with a couple of ways to do this, but none of them are particularly elegant. You can use a complex predicate OR:

 var predicates: [NSPredicate] = [] for item in items { predicates.append(NSPredicate(format: "item = %@ AND endpoint = %@", item, endpoint)) } let compoundPredicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: predicates) let results = try! context.fetch(compoundPredicate) 

Or could you generate an identifier for ItemPosition objects by adding endpoints and item identifiers and selecting them?

0
source

Source: https://habr.com/ru/post/1270687/


All Articles