Predicate matching

It looks like I ran into a major difference tonight between fetch requests and filtering an array on how predicates are evaluated. I’ve been using predicates that look like [NSPredicate predicateWithFormat:@”department == %@”, [someDepartment objectID]] in CoreData fetch requests with no problems. If I used that predicate on against the employee entity, I’d get back an array with all employees that are in someDepartment.

So tonight when I had to filter an array of employee objects I figured I’d use a predicate with the same format and I’d be all set. Boy was I wrong. Unfortunately it appears that relationships are not matched on NSManagedObjectIDs when filtering an array with filteredArrayUsingPredicate:. I get back an empty array. If I change the predicate to [NSPredicate predicateWithFormat:@”department == %@”, someDepartment], I get back the correct objects. The objectIDs are not being checked against target’s ID. As far as I can tell, there’s no documentation on this behavior. So now I get to create a work around for this behavior. If your wondering why I’m using the IDs instead of the actual objects and need to find a workaround, it is because there is some archiving involved and multiple contexts within a single persistence stack.

2 Responses to “Predicate matching”

  1. Peter Hosey Says:

    Would [NSPredicate predicateWithFormat:@”department.objectID == %@”, [someDepartment objectID]] work? (I’ve never used Core Data longer than half an hour, but it would certainly work outside of Core Data.)

  2. brad Says:

    Thanks Peter. That does work and I didn’t think of it last night. I was hung up on the predicates acting differently without being documented. I think I’m still going to rewrite it though. The way I’m thinking of doing it should give me more flexibility if I want to store predicates that match on things like created yesterday.

Leave a Reply