我有一个 JSONModel 对象数组。 JSONModel 对象如下所示
@interface ProductModel : JSONModel
@property(nonatomic, strong) NSString *name;
@property(nonatomic, strong) NSString *price;
@property(nonatomic, strong) NSArray *productCategories;
@end
在 productCategory 模型中我有这个
@interface ProductCategoryModel : JSONModel
@property (nonatomic,assign) NSString *id;
@end
json 看起来像这样
{
"productCount":"129",
"products": [
{
"name": "Art attack",
"price": "$19.99",
"prouctCategories":[
{ "id": "50" }
{ "id": "10" }
]
}
我必须过滤数组,检查数组 productCategories 中 productCategory 的 id 属性。一个产品可以有多个类别。例如,我需要获取 ID 为 10 的产品列表。
我想使用 NSArray 的 filteredArrayUsingPredicate
方法获取该列表,但我找不到正确的谓词格式来获取它。是否可以使用谓词来做到这一点。
我试过这个谓词,但我什么也没得到
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ == '%@"', @"id", @"50"];
最佳答案
NSPredicate文档对于构建此类查询非常清楚。您可以使用 ANY
子句对多对多关系应用过滤器,以获取任何类别 ID 为 10 的产品。
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ANY productCategories.id == '10')"];
NSArray *filteredProducts = [products filteredArrayUsingPredicate:predicate];
关于ios - 在 iOS 中使用谓词过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28376047/