简体   繁体   中英

NSPredicate for property of object in NSArray of NSArray

I have an objects like the below structure: Transaction has an array of Items. Item has an array of SubItems

@interface Transaction : NSObject
@property (nonatomic, copy) NSString *id; 
@property (nonatomic, assign) NSInteger status;
@property (nonatomic, strong) NSArray *items; // array of Item
@end

@interface Item : NSObject
@property (nonatomic, copy) NSString *identifier;
@property (nonatomic, assign) NSInteger price;
@property (nonatomic, strong) NSArray *subitems;
@end


@interface SubItem : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger price;
@end

I would like to create predicate to find name and price of Subitem from NSArray of Transaction

pred = [NSPredicate predicateWithFormat:
                    @"ANY SELF.%K.%K.%K contains %@",
                    @"items",
                    @"subitems",
                    @"name",
                    @"MY_SUB_ITEM_NAME"];

This generates the error below.

failed: caught "NSInvalidArgumentException", "Can't do regex matching on object ( MY_SUB_ITEM_NAME )."

However when I use the similar format to find out properties in Transaction. It works fine.

 pred = [NSPredicate predicateWithFormat:
                    @"SELF.%K LIKE %@",
                    @"identifier",
                    @"TX001"];

How should I correct my predicate to query property in Item and SubItem

I think that cannot work with -predicateWithFormat: for two aggregation levels. On each level you can have a ANY or an ALL aggregation. So the "right" syntax would be ANY items ANY subitems.… = … . Or ANY items ALL subitems.…= …" or …

You can try to build the predicate manually with NSExpression , probably using subqueries.

Oh, you are not using Core Data, what I assumed. So simply do it manually in a loop or use a computed property.

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