如何使用数组过滤数组?

时间:2013-05-07 12:28:50

标签: iphone objective-c nspredicate

我有三种类型的自定义类(见下文)和三种数组componentList,componentGroupList和componentGroupItemList。数组未链接,每个数组都包含所有对象。我需要过滤特定组件,所有相关组及其所有相关项。

现在,我知道如何使用@“componentId == 123”过滤componentList并获得所需的组件对象。我还可以使用相同的谓词从componentGroupList过滤其组,因为ComponentGroup对象包含相同的componentId键。但是,我不知道如何从componentGroupItemList过滤相关的ComponentGroupItem对象。

目前,我已经过滤了包含ComponentGroup对象的数组,我想使用该数组过滤componentGroupItemList。是否可能,或者我是否需要将filteredComponentGroupList中的所有“groupId”值提取为字符串然后生成一些谓词?

课程:

@interface Component : NSObject

  @property (nonatomic, strong) NSNumber *componentId;
  @property (nonatomic, strong) NSString *title;

@end

@interface ComponentGroup : NSObject

  @property (nonatomic, strong) NSNumber *groupId;
  @property (nonatomic, strong) NSNumber *componentId;
  @property (nonatomic, strong) NSString *title;

@end

@interface ComponentGroupItem : NSObject

  @property (nonatomic, strong) NSNumber *itemId;
  @property (nonatomic, strong) NSNumber *groupId;
  @property (nonatomic, strong) NSString *title;

@end

2 个答案:

答案 0 :(得分:3)

您必须首先提取组ID

NSArray *groupIds = [filteredComponentGroupList valueForKey:@"groupId"];

并将其用于谓词

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"groupId IN %@", groupIds];
NSArray *filteredComponentGroupItemList = [componentGroupItemList filteredArrayUsingPredicate:predicate];

答案 1 :(得分:2)

乍一看,您的数据结构似乎有点多余,但我想您已经考虑过了。

如果我正确理解了您的要求,您已经过滤了一组组件组(我们称之为filteredComponentGroups),您希望使用componentGroupItemList过滤另一个数组(filteredComponentGroups)。

在这种情况下,您可以使用IN的{​​{1}}运算符,并在数组上构造带有NSPredicate的ID数组。数组上的valueForKey:构造一个新数组,其中只包含原始集合中每个对象的该键的值。对于像这样的情况非常强大。

valueForKey:

直接在浏览器中输入,因此请注意拼写错误。

相关问题