我正在尝试编写一个谓词来检查我设置的字典中的特定值。
该字典具有“0”、“1”和“2”的字符串版本作为我想要访问的键。
我想写的谓词是:
$player.currencyDictionaries.0.earned > 1000
问题是不允许使用.0。假设我无法轻松更改字典存储值的方式(这是在旧版本中,我想在所有版本上使用相同的谓词,因为它托管在服务器上)有什么方法可以访问数据吗?
I'm trying to write a predicate to check a specific value in a dictionary I have set up.
This dictionary has string versions of "0", "1", and "2" as keys which I would like to access.
The predicate I would like to write is:
$player.currencyDictionaries.0.earned > 1000
The problem is that .0 is not allowed. Assuming I cannot easily change how the dictionary stores values (this is in older versions and I'd like to use the same predicate on all versions as it is hosted on a server) is there any way to access the data?
发布评论
评论(1)
IIRC,您可以这样做:(
您可能需要执行
['0']
以保证传递的值是字符串而不是数字)请注意此语法 (
[0]
) 仅适用于谓词格式字符串。它不适用于关键路径。此语法在“索引表达式”部分。
编辑
实际上,这行不通,原因如下:
字符串
"$player.currencyDictionaries[0].earned"
将被读取并转换为NSExpression
类型为NSKeyPathExpression
。这意味着,当它被评估时,它基本上会获取该字符串并通过接收者的-valueForKeyPath:
方法运行它。正如我上面提到的,括号语法不适用于关键路径,因此这将产生错误的答案。但是,由于您知道
currencyDictionaries
返回一个NSDictionary
,并且由于NSDictionary
覆盖-valueForKey:
方法,可以转动[0]
位通过将其转换为文字字符串来转换为关键路径:IIRC, you can do this:
(You might need to do
['0']
to guarantee that the passed value is a string and not a number)Note that this syntax (
[0]
) only works in predicate format strings. It does not work with key paths.This syntax is defined under the "Index Expression" section of the Predicate BNF.
EDIT
Actually, this won't work, and here's why:
The string
"$player.currencyDictionaries[0].earned"
will be read and turned into anNSExpression
of typeNSKeyPathExpression
. This means, when it's evaluated, it's going to basically take that string and run it through the receiver's-valueForKeyPath:
method. As I mentioned above, the bracket syntax doesn't work with key paths, and thus this will produce the incorrect answer.However, since you know the
currencyDictionaries
returns anNSDictionary
, and sinceNSDictionary
overrides the-valueForKey:
method, you can turn the[0]
bit into a key path, by turning it into a literal string: