I have the need to create a complex predicate for an abstract base object. I want to have separate predicate queries for different inheriting entities and key off the sub-entity type, the example below is what I would like to do, however, I have not been able to find a way to reference the entity name or type in the predicate.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"MyCommonObjectBase" inManagedObjectContext:myContext];
NSPredicate *subclassAPredicate = [NSPredicate predicateWithFormat:@"someValue > %@ && entityName = %@", 100, @"SubclassA"];
NSPredicate *subclassBPredicate = [NSPredicate predicateWithFormat:@"someValue < %@ && entityName = %@", 50, @"SubclassB"];
request.predicate = [NSCompoundPredicate orPredicateWithSubpredicates:[NSArray arrayWithObjects:subclassAPredicate, subclassBPredicate, nil]];
I got a response from Apple at http://bugreport.apple.com problem number 7318897:
So it seems the proper solution is to have separate fetch requests and to merge the result sets after execution.
A shot in the dark here, but what about using the
className
value in the predicate?(Notice that you had an error in your predicate format. You were using
%@
to try and substitute in an integer value (100
).%@
is only used for objects. Use%d
(or some other flavor) for primitives)EDIT Found it!
You'll want to do this:
I just tested this on one of my apps and it seems to work.
-Another edit-
Here's the test that I ran, which seemed to work:
When I run that,
a
logs two NSManagedObjects, both of the@"DefaultFolder"
variety (which is what I was expecting). (AbstractFolder
is an abstract entity. One of the child entities that inherits from it is aDefaultFolder
)The only way of associating a predicate with an entity I know of like is this:
Maybe you were referring to the field name?
Edit: the entity is associated with the request, not with the predicate.