在应用 NSPredicate 时转换 NSDictionary 值?
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
Try this:
你的问题不是谓词;而是谓词。您的问题是您正在处理
NSString
对象,而不是处理NSNumber
对象。我会首先将时间集中在将它们更改为 NSNumbers 上,然后验证它是否不起作用。仅供参考,JSON 框架 会自动将数字解析为
NSNumbers
...Your problem isn't the predicate; your problem is that you're dealing with
NSString
objects instead of dealing withNSNumber
objects. I would focus my time on changing them toNSNumbers
first, and then verify that it's not working.FYI, the JSON Framework does automatic parsing of numbers into
NSNumbers
...