NSPredicate与嵌套数组 [英] NSPredicate with nested arrays
问题描述
我具有以下对象结构
类别:
- 子类别(子类别的nsarray)
子类别:
- 问题(问题nsarray)
问题:
-
问题(nsstring)
question (nsstring)
answer(nsstring)
answer (nsstring)
我需要的是使用给定的子字符串搜索任何问题
What I need is to search any question with the given substring
以下谓词不起作用:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY subcategories.questions.question CONTAINS[cd] %@", substring];
如何正确获取它们?
推荐答案
我认为这种极端嵌套的数据是一个非常糟糕的主意.它过于复杂且容易出错.许多事情都不直观.例如,您的谓词将在存在某些与您的查询匹配的问题时获取所有类别.您仍将获得整个类别,包括所有与查询不匹配的问题.要向下钻取,您将不得不再次过滤.
I think this kind of extreme nested data is a very bad idea. It is overly complicated and error prone. Many things are not intuitive. For instance, your predicate would fetch all categories where there is some question that matches your query. You would still get the whole category back, including all questions that do not match the query. To drill down, you would have to filter again.
对于这种设置,我非常推荐使用Core Data.您可能只需要提取必要的问题,因为在核心数据中,关键路径在两个方向上均有效,而这正是您所需要的.
For this kind of setup, I very much recommend Core Data instead. You could just fetch the necessary questions because in Core Data key paths work in both directions, which is what you need here.
对于您的特定问题,您将获取与谓词匹配的 Question
实例
For your particular problem, you would fetch the Question
instances that match the predicate
[NSPredicate predicateWithFormat:@"question CONTAINS[cd] %@", substring];
您将获得所有类别的清单,并带有简洁的表达式,例如
You would get a list of all categories with a succinct expression like
[questions valueForKeyPath:@"subcategory.category"];
这篇关于NSPredicate与嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!