NSPredicate ANY 只返回与字符串列表中第一个元素的关键字匹配的记录

Posted

技术标签:

【中文标题】NSPredicate ANY 只返回与字符串列表中第一个元素的关键字匹配的记录【英文标题】:NSPredicate ANY only returning records which match the keyword of their first element in list of strings 【发布时间】:2021-07-28 18:43:09 【问题描述】:

我有一个 CKRecordType 填充食谱,其中包括成分字符串列表。如何查询在成分列表中任意位置包含两种成分的食谱列表?

    let predicate = NSPredicate(format: "ANY ingredients == %@","egg")

这是上述查询返回的列表,请注意返回的食谱只是第一个成分是“鸡蛋”的食谱。

Name: 1 minute breakfast sandwich
Recipe_id: 533190
Ingredients:
    0: egg
    1:  milk
    2:  salt
    3:  pepper
    4:  cooking spray
    5:  english muffin
    6:  cheese
    7:  bacon
    8:  tomatoes
    9:  basil
    10:  avocado
    11:  red pepper flakes"
Name: caesar dressing
Recipe_id: 528367
Ingredients:
    0: egg
    1:  egg yolk
    2:  white wine vinegar
    3:  lemon
    4:  juice of
    5:  salt
    6:  fresh ground black pepper
    7:  mustard powder
    8:  cayenne
    9:  white pepper
    10:  parmigiano-reggiano cheese
    11:  extra virgin olive oil
    12:  thai fish sauce
    13:  garlic cloves"
Name: cajun hush puppies
Recipe_id: 503126
Ingredients:
    0: egg
    1:  buttermilk
    2:  green onion
    3:  water
    4:  cornmeal
    5:  flour
    6:  brown sugar
    7:  baking powder
    8:  baking soda
    9:  salt
    10:  ground red pepper
    11:  vegetable oil"

【问题讨论】:

【参考方案1】:

我想通了,这就是我解析 csv 的方式。请注意,第一个成分是唯一以空格开头的成分。

所以,我运行这个:

let predicate = NSPredicate(format: "ANY ingredients == %@"," egg")

与此相反:

let predicate = NSPredicate(format: "ANY ingredients == %@","egg")

我得到的结果是“鸡蛋”位于成分列表的中间,如下所示:

Name: carrot apple zucchini bread
Recipe_id: 537241
Ingredients:
    0: unsalted butter
    1:  granulated sugar
    2:  eggs
    3:  fresh orange juice
    4:  vanilla extract
    5:  all-purpose flour
    6:  salt
    7:  baking powder
    8:  baking soda
    9:  cinnamon
    10:  ground cloves
    11:  ground nutmeg
    12:  carrots
    13:  zucchini
    14:  apple
    15:  pecans
    16:  cream cheese
    17:  butter
    18:  powdered sugar
    19:  orange juice
    20:  water"
Name: amish triple butter biscuits
Recipe_id: 536384
Ingredients:
    0: flour
    1:  salt
    2:  cream of tartar
    3:  sugar
    4:  baking powder
    5:  butter
    6:  egg
    7:  milk"
Name: blueberry cheesecake crumb cake
Recipe_id: 535644
Ingredients:
    0: flour
    1:  baking powder
    2:  salt
    3:  butter
    4:  lemon
    5:  light brown sugar
    6:  sugar
    7:  eggs
    8:  vanilla
    9:  mascarpone
    10:  cream cheese
    11:  caster sugar
    12:  cornstarch
    13:  blueberries
    14:  powdered sugar
    15:  milk"

【讨论】:

以上是关于NSPredicate ANY 只返回与字符串列表中第一个元素的关键字匹配的记录的主要内容,如果未能解决你的问题,请参考以下文章

在 NSPredicate 中使用 ALL/ANY/NONE

使用 ANY 和两个条件创建 NSPredicate

NSPredicate 使用 CoreData 进行多个 ANY 查询

CloudKit,NSPredicate在私有容器中返回计数或确定是否存在任何记录?

Core Data NSPredicate 过滤结果

在保存到核心数据之前将字符串与 NSPredicate 进行比较