NSPredicate与自定义对象的嵌套数组混淆

时间:2016-04-05 17:15:18

标签: objective-c nsarray nspredicate

我有一个自定义对象,格式为:

@interface GroupModel : NSObject

@property (strong, nonatomic) NSString *groupId;
@property (strong, nonatomic) NSArray *children;
@property (strong, nonatomic) NSArray *instruments;
@property (strong, nonatomic) NSString *name;

@end

instruments数组是一系列自定义模型,形式为:

@interface InstrumentModel : NSObject

@property (strong, nonatomic) NSString *instrumentId;
@property (strong, nonatomic) NSString *name;

@end

GroupModel中的children数组是GroupModel对象的数组。 这背后的原因是创建一个树状结构,因此根组可以有多个子组,每个子组可以包含工具和/或子组。

有点像文件夹/文件格式

现在我正在尝试的是在给定的GroupModel中搜索给定的工具ID。 instrumentId可能位于仪器阵列中的给定模型中,也可能位于任何子组模型仪器阵列中。

我需要使用什么样的谓词,因为我很困惑。 这需要子查询吗?

1 个答案:

答案 0 :(得分:0)

好的,这对我有用:

            //Create an array to add all InstrumentGroup Objects
            NSMutableArray * allChildren = [NSMutableArray new];

            //add the root group instruments
            [allChildren addObjectsFromArray:rootGroup.instruments];
            //now add the children's of children Instruments using the unionOfArrays Collection operator
            [allChildren addObjectsFromArray:[rootGroup.children valueForKeyPath:@"@unionOfArrays.instruments"]];
            //add the children's children instruments
            [allChildren addObjectsFromArray:[rootGroup.children valueForKeyPath:@"@unionOfArrays.children.@unionOfArrays.instruments"]];

            //filter the Instrument objects
            predicate = [NSPredicate predicateWithFormat:@"ANY instruments.instrumentId == %@",selectedInstrumentId];
            filtered = [allChildren filteredArrayUsingPredicate:predicate];

            if (filtered.count>0) {
                //found the instrument!
                InstrumentModel *instrument = filtered.firstObject;
            }