dyatesupnorth
dyatesupnorth

Reputation: 830

Quick and easy way to query all entities in Core Data

Is there a way to perform an NSPredicate request against multiple entities at once?

I have a dozen entities, each with an hasChanged field, I need to check if any of these entities has changed, apart from doing each one separately (like i'm doing below) is there a better method / approach?

                    let entityName = "Work"
                var request = NSFetchRequest(entityName: entityName)
                request.predicate = NSPredicate(format: "hasChanged ==", true)

Upvotes: 0

Views: 119

Answers (1)

Bart Hopster
Bart Hopster

Reputation: 252

The only way to achieve this, is using entity inheritance. Create an abstract class and define it as the parent of all the entities you want to check. Give this abstract class the hasChanged property and remove the property from your entity classes.

In this way, you can perform a NSFetchRequest on the abstract entity and retrieve all entities' objects.

let entityName = "YourAbstractEntity"
var request = NSFetchRequest(entityName: entityName)
request.predicate = NSPredicate(format: "hasChanged == true")

However, there's a downside. All instances of that abstract entity will be placed in the same table of your database. The more entities (and instances of these entities) you save, the less performing your database will be.

Upvotes: 2

Related Questions