If you have an array of object IDs, you can fetch all of the objects for those IDs at once with the right predicate. It would be something like
let objectIDs: [NSManagedObjectID] = // Your object IDs from a previous fetch
let predicate = NSPredicate(format: "self in %@", objectIDs)
Then use that predicate in a fetch.
That predicate says to get every object with an object ID in the array. Newer objects of the same type won't be included.
Additional: The "map" approach mentioned by @vadian would be something like this, where MyClass
is the name of your managed object class:
let results: [MyClass] = objectIDs.compactMap { try? context.existingObject(with: $0) as? MyClass }
With this code, you need to use existingObject(with:)
instead of object(with:)
because you mentioned that you might have deleted some of the objects. Using object(with:)
in that case could get you some bogus results, because that function always returns a managed object even if there isn't one with the object ID.
If you only have a few object IDs, performance is probably very similar for each of these approaches. With larger collections I suspect that compactMap
would be slower because it needs to ask the context for each object individually. The predicate approach asks for everything at once and lets SQLite handle the lookup. I'm not certain about the comparison though, so it's possible it's the other way around for some reason.