0

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)
dyatesupnorth
  • 790
  • 4
  • 15
  • 45

1 Answers1

2

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.

Bart Hopster
  • 252
  • 1
  • 4
  • ahh but there is hasChanged property on each entity, which i need to check – dyatesupnorth Aug 31 '15 at 14:35
  • 1
    When the abstract entity has the "hasChanged" property, all inheriting entities will have this property too. The code I gave above covers all inheriting entities with the "hasChanged" property set to "true". – Bart Hopster Aug 31 '15 at 14:40
  • that makes sense, how do i setup the abstract entity? I know I can tick the 'abstract entity' box in the data model editor, but apart from that im a little lost, like, do I need to define any relationships etc? – dyatesupnorth Aug 31 '15 at 16:09
  • 1
    But see this SO question, which suggests that having all your entities inherit from an abstract class may create performance issues and may otherwise not be a good idea: http://stackoverflow.com/questions/6917494/core-data-performance-with-single-parent-entity . – Aaron Rasmussen Aug 31 '15 at 17:44
  • @fr0s1yjack: all you need to know can be found [here](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Inheritance.html) and [here](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdMOM.html). It will be quite easy. – Bart Hopster Sep 01 '15 at 07:01