Objective c NSPredicate与自定义对象的嵌套数组混淆
我有一个自定义对象,其格式为:Objective c NSPredicate与自定义对象的嵌套数组混淆,objective-c,nsarray,nspredicate,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; @en
@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中的子数组是GroupModel对象的数组。
这背后的原因是创建树状结构,因此根组可以有多个子组,每个子组都可以包含工具和/或子组
有点像文件夹/文件格式
现在我尝试的是在给定的GroupModel中搜索给定的仪器Id。
instrumentId可能位于instruments数组中的给定模型中,也可能位于任何子组models instruments数组中
我很困惑,我需要使用哪种谓词。
这需要子查询吗?好的,这对我来说很有用:
//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;
}