简体   繁体   中英

Filtering an array of managed objects by another array of managed objects

I have a mutable array of managed objects that I get from Core Data - let's call them ObjectA. ObjectA has a many-to-many relationship with ObjectB, such that each ObjectA has an NSSet of ObjectBs. ObjectB has a one-to-many relationship with ObjectC, ie each ObjectB has one ObjectC.

Now that that's clear (hopefully), here is what I want to do: I want to filter my array of ObjectAs based on the name of a given ObjectC. In other words, I start with an array of all my ObjectAs in Core Data, and I want to end up with only the ObjectAs that own an ObjectB whose ObjectC is named "Potatoes" (for example). I hope that makes sense...here's a dummy situation: a person (ObjectA) can have many songs (ObjectB), and songs can be owned by many people. I have an array of every person, but I want only the people who have songs that belong to a specific album (objectC). Hopefully that helps to clarify the situation.

So, does anyone have any advice on how to best filter through my ObjectAs based on a given ObjectC? I could certainly brute force it with a bunch of loops and ifs, but I'm wondering if there's a more efficient way to do it in fewer steps with something like NSPredicate (which I've used before, but not in a multi-layered situation like this).

Any suggestions would be appreciated!

EDIT

here is a diagram of my model:

模型图

If I understand your problem correctly, the following fetch request should work:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ObjectA"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY objectBs.objectC.name = %@", @"Potato"];
request.predicate = predicate;

NSError *error;
NSArray *result = [context executeFetchRequest:request error:&error];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM