在应用NSPredicate时投射NSDictionary值?

时间:2010-05-11 19:37:29

标签: cocoa nsdictionary nspredicate

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

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

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

我相信如果“distanceInMeters”键的值是NSNumber,这会有效,但因为我从JSON文件中得到它,所以一切都是NSStrings。 上面给出了这个错误:****** - [NSCFNumber length]:无法识别的选择器发送到实例0x3936f00 ***

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

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

希望有人可以帮助我:)。

2 个答案:

答案 0 :(得分:7)

试试这个:

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

答案 1 :(得分:0)

你的问题不是谓词;你的问题是你正在处理NSString个对象而不是处理NSNumber个对象。我会把时间集中在将它们更改为NSNumbers,然后验证它是否无效。

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