I am having issues with subqueries in the predicate for the fetch request of an NSFetchResultsController. Basically the object I'm fetching on has a to-One relationship that has a to-Many relationship that I am performing the subquery on, so it looks like this Target <<--> Person <<-->> ExtendedProperty. I am fetching all targets that have a specific name/value in the extendedProperty of the target's person.
Here is what my predicate looks like
request.predicate = NSPredicate(format: "SUBQUERY(person.extendedProperties, $extProp, $extProp.name == %@ && $extProp.value == %@).@count > 0", "favorite color", "red")
When I try to use this I don't get any results and the console outputs
2015-09-08 17:33:26.206 CoreDataBug[2019:313174] CoreData: error: (1) I/O error for database at /var/mobile/Containers/Data/Application/EAFFE09B-D259-4917-A13F-2D46D0D81816/Documents/CoreDataBug.sqlite. SQLite error code:1, 'no such column: t2.ZNAME'
I'm trying to figure out if I'm doing something wrong or if there is an Apple bug I should file. I set it up to print out the SQL and it looks like it's joining the join table for the extendedProperty object but not it's actual data table and that is the reason why it isn't finding the column. So it looks like either this is an Apple bug, or I'm not allowed to have a relationship in the collection definition portion of the subquery.
I also have a very simple sample project that illustrates this issue on github at https://github.com/costonb/coreDataBugExample
I know of two ways that I can adjust the project to fix this. I can make contacts a to-Many relationship and have nested subpredicates. This would mean that my data wouldn't correctly reflect how the objects are supposed to be since a target will always have only a single contact.
The other option is to pre-fetch the extended properties and then use these in a fetch on targets. This would require two fetches though and therefore would likely be much slower.