在iOS中使用谓词过滤数组

时间:2015-02-06 22:38:40

标签: 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"];

3 个答案:

答案 0 :(得分:1)

NSPredicate文档非常清楚构建此类查询。您可以使用ANY子句对多对多关系应用过滤器,以获取任何类别ID为10的产品。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ANY productCategories.id == '10')"];

NSArray *filteredProducts = [products filteredArrayUsingPredicate:predicate];

答案 1 :(得分:0)

为简化问题,请将json更改为:

{
"productCount":"129",

"products": [
    {
        "name": "Art attack",
        "price": "$19.99",
        "productCategories":["50","10"]
}

所以你可以使用这样的谓词:

[NSPredicate predicateWithFormat:@"productCategories CONTAINS '10')"]

答案 2 :(得分:0)

您可以使用NSPredicate,因为您的json就像

{
"productCount":"129",

"products": [
    {
        "name": "Art attack",
        "price": "$19.99",
        "prouctCategories":[

            { "id": "50" }

            { "id": "10" }

         ]

}

然后你可以用它来检查:

NSArray *arrFiltered = [arrProducts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(self.prouctCategories.id == '10')"]];

或者您也可以更改您的json格式,以便更轻松地使用

{
"productCount":"129",

"products": [
    {
        "name": "Art attack",
        "price": "$19.99",
        "prouctCategories":[

            { "id": 50,10,20 }

         ]

}

所以你可以像这样过滤id

NSArray *arrFiltered = [arrProducts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(self.prouctCategories.%K CONTAINS '10')", 'id']];

希望它会对你有所帮助。 :)