在应用 NSPredicate 时转换 NSDictionary 值?

发布于 2024-09-01 08:33:41 字数 648 浏览 13 评论 0原文

我有一个 NSDictionary 对象数组。 这些字典是从 JSON 文件解析的。 NSDictionary 中的所有值对象都是 NSString 类型,其中一个键称为“distanceInMeters”。

我计划使用 NSPredicate 来过滤这些数组,所以我是这样开始的:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(distanceInMeters <= %f)", newValue];
NSArray *newArray = [oldArray filteredArrayUsingPredicate:predicate];

我相信如果“distanceInMeters”键的值是 NSNumber,那么这会起作用,但因为我从 JSON 文件中获得它,所以一切都是 NSString。 上面给出了这个错误:****** -[NSCFNumber length]: unrecognized selector sent to instance 0x3936f00***

这是有道理的,因为我刚刚尝试将 NSString 视为 NSNumber。

有没有办法在过滤字典时从字典中转换值,或者可能有一种完全不同的方法来解决这个问题?

希望有人能帮助我:)

I have an Array of NSDictionary objects.
These Dictionaries are parsed from a JSON file.
All value objects in the NSDictionary are of type NSString, one key is called "distanceInMeters".

I had planned on filtering these arrays using an NSPredicate, so I started out like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(distanceInMeters <= %f)", newValue];
NSArray *newArray = [oldArray filteredArrayUsingPredicate:predicate];

I believe this would have worked if the value for the "distanceInMeters" key was an NSNumber, but because I have it from a JSON file everything is NSStrings.
The above gives this error:****** -[NSCFNumber length]: unrecognized selector sent to instance 0x3936f00***

Which makes sense as I had just tried to treat an NSString as an NSNumber.

Is there a way to cast the values from the dictionary while they are being filtered, or maybe a completely different way of getting around this?

Hope someone can help me :)

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

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

发布评论

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

评论(2

往日 2024-09-08 08:33:41

试试这个:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(distanceInMeters.floatValue <= %f)", newValue];

Try this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(distanceInMeters.floatValue <= %f)", newValue];
土豪 2024-09-08 08:33:41

你的问题不是谓词;而是谓词。您的问题是您正在处理 NSString 对象,而不是处理 NSNumber 对象。我会首先将时间集中在将它们更改为 NSNumbers 上,然后验证它是否不起作用。

仅供参考,JSON 框架 会自动将数字解析为 NSNumbers...

Your problem isn't the predicate; your problem is that you're dealing with NSString objects instead of dealing with NSNumber objects. I would focus my time on changing them to NSNumbers first, and then verify that it's not working.

FYI, the JSON Framework does automatic parsing of numbers into NSNumbers...

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