访问 NSPredicate 中的数字 NSDictionary 键

发布于 2024-12-28 21:15:27 字数 234 浏览 1 评论 0 原文

我正在尝试编写一个谓词来检查我设置的字典中的特定值。

该字典具有“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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

做个ˇ局外人 2025-01-04 21:15:27

IIRC,您可以这样做:(

$player.currencyDictionaries[0].earned > 1000

您可能需要执行 ['0'] 以保证传递的值是字符串而不是数字)

请注意此语法 ([0] ) 适用于谓词格式字符串。它不适用于关键路径。

此语法在“索引表达式”部分。


编辑

实际上,这行不通,原因如下:

字符串 "$player.currencyDictionaries[0].earned" 将被读取并转换为 NSExpression 类型为 NSKeyPathExpression。这意味着,当它被评估时,它基本上会获取该字符串并通过接收者的 -valueForKeyPath: 方法运行它。正如我上面提到的,括号语法不适用于关键路径,因此这将产生错误的答案。

但是,由于您知道 currencyDictionaries 返回一个 NSDictionary,并且由于 NSDictionary 覆盖-valueForKey:方法,可以转动[0]位通过将其转换为文字字符串来转换为关键路径:

$player.currencyDictionaries.'0'.earned

IIRC, you can do this:

$player.currencyDictionaries[0].earned > 1000

(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 an NSExpression of type NSKeyPathExpression. 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 an NSDictionary, and since NSDictionary overrides the -valueForKey: method, you can turn the [0] bit into a key path, by turning it into a literal string:

$player.currencyDictionaries.'0'.earned
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文