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, i.e. each ObjectB has one ObjectC.
我有一个可变的托管对象数组,我从Core Data获得 - 让我们称之为ObjectA。 ObjectA与ObjectB具有多对多关系,因此每个ObjectA都有一个ObjectBs的NSSet。 ObjectB与ObjectC有一对多的关系,即每个ObjectB都有一个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.
现在这很清楚(希望如此),这就是我想要做的:我想根据给定ObjectC的名称过滤我的ObjectAs数组。换句话说,我从核心数据中的所有ObjectAs数组开始,我想最终只得到拥有ObjectB的ObjectAs,其ObjectC被命名为“Potatoes”(例如)。我希望这是有道理的......这是一个虚拟的情况:一个人(ObjectA)可以有很多歌(ObjectB),歌曲可以被许多人拥有。我有一个每个人的阵列,但我只想要拥有属于特定专辑(objectC)的歌曲的人。希望这有助于澄清情况。
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).
那么,有没有人对如何根据给定的ObjectC最佳地过滤我的ObjectAs有任何建议?我当然可以通过一堆循环和ifs来强制它,但我想知道是否有更有效的方法以更少的步骤使用NSPredicate(我之前使用过,但不是多层次)像这样的情况)。
Any suggestions would be appreciated!
任何建议,将不胜感激!
EDIT
here is a diagram of my model:
这是我的模型图:
1 个解决方案
#1
3
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];
#1
3
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];