ios - 在 iOS 中使用谓词过滤数组

标签 ios arrays filter

我有一个 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/

相关文章:

iphone - 分段线仅在iPhone上绘制第一段。在模拟器中完美工作

ios - 当按下 uicollectionviewcell 中的某些内容时如何通知 Controller

iphone - iOS:预计算 UITableView 的行高

c++ - 指向数组访问的指针出现段错误

基于第一个 future 结果的Scala future 返回

ios - 验证期间的 iTunes 连接架构问题

java - 我在 Java 中的快速排序算法出现问题

javascript - 如何使用循环比较两个对象与嵌套对象数组

python - 合并列上的 DataFrame 列表?

ios - 比较值并在 uitableview 中显示特定结果