OGeek|极客世界-中国程序员成长平台

标题: ios - NSArray 的 NSArray 中对象属性的 NSPredicate [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 10:08
标题: ios - NSArray 的 NSArray 中对象属性的 NSPredicate

我有一个类似以下结构的对象: Transaction 有一个 Items 数组。 Item 有一个 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

我想创建谓词以从 NSArray of Transaction 中查找 Subitemnameprice p>

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

这会产生以下错误。

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

但是,当我使用类似的格式来查找 Transaction 中的属性时。它工作正常。

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

我应该如何更正我的谓词以查询 ItemSubItem

中的属性



Best Answer-推荐答案


我认为这不能与 -predicateWithFormat: 一起用于两个聚合级别。在 每个 级别上,您可以有一个 ANY 或一个 ALL 聚合。所以“正确”的语法应该是 ANY items ANY subitems.... = ...。或 ANY items ALL subitems....= ..." 或 ...

您可以尝试使用 NSExpression 手动构建谓词,可能使用子查询。

哦,我假设你没有使用 Core Data。因此,只需在循环中手动执行或使用计算属性即可。

关于ios - NSArray 的 NSArray 中对象属性的 NSPredicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32263367/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4