配置具有多个条件的NSPredicate

Wil*_*ill 29 iphone xcode core-data objective-c ios

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

我对Core Data很新,不确定这是否是实现我想要做的正确方法.

这是我想要做的:

有一个Photo对象与Location对象具有whereTook关系,该对象具有photosTookThere的反转.

Photo依次具有名为isFavourite的NSNumber属性.

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

这是迄今为止的代码:

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

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

Mar*_*ard 63

只需将每个条件放在括号内并用AND连接它们.

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

我还建议将"whereTook"关系的名称更改为"location",将"photosTookThere"更改为"照片",这更符合惯例.


Wil*_*ill 8

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

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


小智 6

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

  • @katzenhut单个```=```是谓词/ SQLite的有效条件. (2认同)