0

EntityA has a to-many relationship to EntityB (and EntityB has a to-one relationship to EntityA). I have an array of EntityBs (or more accurately, I have an NSArray that contains instances of NSManagedObject which represent EntityB). I want to create an NSFetchRequest that will fetch all EntityAs that have a relationship to at least one of the EntityBs in the array. How do I write the predicate for this fetch request?

The following works, but I think it is sub-optimal; it's hard to grok and I'm sure there must be a better way of expressing this:

NSArray *entityBs = ...;
NSMutableArray *containsEntityBSubPredicates = [NSMutableArray new];
for (NSManagedObject *entityB in entityBs) {
    [containsEntityBSubPredicates addObject:[NSPredicate predicateWithFormat:@"%@ IN entityBs", entityB]];
}
NSPredicate *containsEntityBsPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:containsEntityBSubPredicates];

I've also tried this, but it doesn't work:

NSArray *entityBs = ...;
NSPredicate *containsEntityBsPredicate = [NSPredicate predicateWithFormat:@"ANY %@ in entityBs", entityBs];

Am I missing a simpler solution?

4

1 回答 1

1

您的谓词几乎就在那里,只需切换参数:

[NSPredicate predicateWithFormat:@"ANY entityBs in %@", entityBArray];

IN 在此处查看 Apple 的示例代码以获得进一步的解释。

于 2013-04-18T09:13:00.417 回答