使用多个条件配置 NSPredicate



我不确定如何将几个条件"级联"到NSPredicate中。

我对Core Data相当陌生,不确定这是否是实现我想要做的事情的正确方法。

这是我正在尝试做的:

有一个 Photo 对象与 Location 对象具有 whereTaken 关系,该对象与 photosTookThere 相反。

反过来,照片具有一个名为isFavorite的NSNumber属性。

我想配置一个NSFetchRequest,它将首先检查照片是否存在,如果是,请检查每个生成的照片对象并仅返回设置为收藏夹的对象。

这是到目前为止的代码:

request.entity = [NSEntityDescription entityForName:@"Location" inManagedObjectContext:context];
request.sortDescriptors = [NSArray arrayWithObject[NSSortDescriptorsortDescriptorWithKey:@"locationId" ascending:YES]];
request.predicate = [NSPredicate predicateWithFormat:@"photosTookThere.@count != 0"];

如何将第二个条件级联到谓词中并返回正确的结果?

只需将每个条件放在括号内并将它们与 AND 连接即可。

[NSPredicate predicateWithFormat:@"(photosTookThere.@count != 0) AND (isFavourite == %@)", [NSNumber numberWithBool:YES]];

我还建议将"whereTook"关系的名称更改为"位置",将"photosTookThere"更改为简单的"照片",这更符合惯例。

我最终能够使用子查询解决这个问题:

request.predicate = [NSPredicate predicateWithFormat:
                         @"(photosTookThere.@count !=0) AND SUBQUERY(photosTookThere, $Photo, $Photo.isFavourite==1).@count >0"
                         ];

您可以非常简单地在谓词中使用 AND 和 OR,就像在 SQL 语句中指定"where"条件一样。 要检查 NULL,在与 "whereTook" 进行比较时,它看起来像您想要的,您可以与 nil (whereTaken = nil) 进行比较。

最新更新