NSPredicate, get results with a subset of one-to-many relationship

孤街浪徒 提交于 2019-12-01 00:35:21

What you want to achieve could be reached in two ways:

using a SUBQUERY

[NSPredicate predicateWithFormat:@"SUBQUERY(dataLines, $x, $x.theWeek == %@).@count > 0)", [NSNumber numberWithInt:18]];

or the ANY modifier

[NSPredicate predicateWithFormat:@"ANY dataLines.theWeek == %@", [NSNumber numberWithInt:18]];

You can do also the following if you need to check against multiple values:

[NSPredicate predicateWithFormat:@"SUBQUERY(dataLines, $x, $x.theWeek == %@ or $x.theWeek == %@).@count > 0)", [NSNumber numberWithInt:18], [NSNumber numberWithInt:19]];

The same can be applied to ANY modifier. ANY ... OR ANY ....

Maybe if you share some code we could help you.

P.S. I suppose you don't use scalar values and theWeek is a number.

Hope it helps.

You should fetch the dataLine property instead. Assuming your Product and dataLine entity connected by relationship someRelation then you can try this code;

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityWithName:@"dataLine" inManagedObjectContext:self.managedObjectContext]];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"dataLines.week == %@",theWeek]];

NSMutableArray *tmpProduct [[NSMutableArray init] alloc];
NSMutableArray *tmpArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

for (dataLine *theDataLine in tmpArray);
NSLog(@"%@",theDataLine.someRelation.name);
tmpProduct = theDataLine.someRelation.name;

then you can just call tmpProduct to call or display your product in table view

Create a fetch request for the 'Product' entity:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity: [NSEntityDescription entityForName:@"Product" ...]]

then create a predicate using the properties/attributes of Product with 'ANY':

[fetchRequest setPredicate:
  [NSPredicate predicateWithFormat:@"ANY dataLines.theWeek == %@", <whatever week>]];

then execute the fetch to get an array of Product with at least one <whatever week>.

Generally see 'Fetching Managed Objects', NSPredicate and related documentation.

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