Core Data, try to use NSPredicate to filter a toMany relationship set but get the “to-many key not allowed here” error

余生长醉 提交于 2019-12-02 16:26:33

Your problem is that the relationship of one of you keypath is a to-many, to-many and the predicate does not know which particular object goes with which.

You have ThemeEntities<<-->>Quotes which is produces a set at each end. The quotes.author.alias keypath says "a set of quotes instances, each linked to author instances which in turn has an alias attribute." The predicate cannot process the set.

You need to use a subquery to jump a to-many keypath. The subquery is essentially a nested predicate which searches a set and returns another set of objects matching the nested predicate. Subqueries are poorly documented but they have the form:

SUBQUERY(collectionName,$collectionElementVariable,expression-with-$collectionElementVariable)

In this case, you are looking for any quote instances that has a author relationship with an alias matching the supplied string. Your predicate would need to look like:

@"theme.name_en=%@ AND (0!=SUBQUERY(quotes,$eachQuote,$eachQuote.author.alias=%@).@count)",@"mytheme", @"myauthor"

The subquery says, "Of the set of quotes, take each quote object and test if its author relationship object has an alias attribute matching 'myauthor'. Count the number of quote objects with that match. If the number is non-zero, return TRUE."

You need to use subqueries whenever you walk a keypath across a to-many relationship.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!