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

标题: ios - 从 NSMutableDictonary 中添加特定键的值(使用 NSPredicate) [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:38
标题: ios - 从 NSMutableDictonary 中添加特定键的值(使用 NSPredicate)

我有以下 JSON 响应,它已存储在 NSMutableDictonary 中。我想添加 special_item 的所有 price

{
    "order_id": "1",
    "order_name": "xyz",
    "order_item": [
        {
            "item_id": "1",
            "item_name": "myone",
            "special_item": [
                {
                    "s_item_id": "1",
                    "price": "10"
                },
                {
                    "s_item_id": "2",
                    "price": "100"
                }
            ]
        },
        {
            "item_id": "2",
            "item_name": "mytwo",
            "special_item": [
                {
                    "s_item_id": "11",
                    "price": "15"
                },
                {
                    "s_item_id": "22",
                    "price": "110"
                }
            ]
        }
    ]
}

是否可以使用 NSPredicate 添加所有 price ?或如何使用 NSPredicate 获取所有 price 值的数组?(例如:[@10,@100,@15,@110])
< br/> 谢谢!



Best Answer-推荐答案


就是这么简单

你可以试试下面的代码

NSArray *arr = [dix valueForKeyPath"order_item.special_item.price"];
long total = 0;
for (id price in arr) {
    if ([price isKindOfClass:[NSArray class]]) {
        total += [[price valueForKeyPath"@sum.self"] longValue];
    }
    else {
        total += [price longValue];
    }
}

关于ios - 从 NSMutableDictonary 中添加特定键的值(使用 NSPredicate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31043172/






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