简体   繁体   English

使用谓词过滤字典数组

[英]Filter an Array of Dictionaries by using a Predicate

I have the following array of dictionaries: 我有以下几本字典:

Printing description of newOrderbookBids:
<__NSArrayI 0x10053e7c0>(
{
    price = "10.14";
    size = 148;
},
{
    price = "10.134";
    size = 0;
},
{
    price = "10.131";
    size = 321;
})

Each dictionary in the array has the keys price and size , both are numbers. 数组中的每个字典都有键pricesize ,它们都是数字。

I would like to return a filtered array which contains only the dictionaries for which size > 0 . 我想返回一个仅包含size > 0的字典的过滤数组。 In this example, this would be the array with dictionary #1 and #3, but without dictionary #2: 在此示例中,这将是具有字典#1和#3但没有字典#2的数组:

   ({
        price = "10.14";
        size = 148;
    },
    {
        price = "10.131";
        size = 321;
    })

I have tried the following code snippet to filter my NSArray *newOrderbookBids by size: 我尝试了以下代码片段按大小过滤我的NSArray *newOrderbookBids

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"size > 0"];
newOrderbookBids = [newOrderbookBids filteredArrayUsingPredicate:predicate];

Unfortunately my code crashes with the runtime error 不幸的是,我的代码因运行时错误而崩溃

[NSSymbolicExpression compare:]: unrecognized selector sent to instance xxxx

What is wrong with my code and predicate? 我的代码和谓词有什么问题? How can I filter by size > 0 ? 如何按size > 0过滤?

Thank you! 谢谢!

"SIZE" is a reserved keyword in the "Predicate Format String Syntax" and the keywords are case-insensitive. “ SIZE”是“谓词格式字符串语法”中的保留关键字,并且该关键字不区分大小写。

To solve that problem, use the "%K" format argument as a var arg substitution for a key path : 要解决该问题,请使用“%K”格式参数作为键路径的var arg替代:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K > 0", @"size"];

Reserved Words 保留字

The following words are reserved: 以下是保留字:

AND, OR, IN, NOT, ALL, ANY, SOME, NONE, LIKE, CASEINSENSITIVE, CI, MATCHES, CONTAINS, BEGINSWITH, ENDSWITH, BETWEEN, NULL, NIL, SELF, TRUE, YES, FALSE, NO, FIRST, LAST, SIZE, ANYKEY, SUBQUERY, CAST, TRUEPREDICATE, FALSEPREDICATE 并且,或者,不是(不是)所有,任何,某些,无,类似,不区分大小写,CI,匹配,包含,开头,结尾,介于,NULL,NIL,自我,TRUE,YES,FALSE,NO,FIRST,LAST,LAST,大小,任意键,子查询,投射,真伪,伪伪

A clearer error message when this happens would be nice. 发生这种情况时,更清晰的错误消息会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM