NSPredicate for property of object in NSArray of NSArray

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

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

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!