NSPredicate:如何将字符串视为数字?

use*_*739 3 xcode core-data nspredicate ios

我正在构建一个复合NSPredicate来在iOS应用程序中使用sqlite上的核心数据进行获取请求.一切都已经正常,但我无法包括最后一个条件.原因很简单:我需要检查存储为字符串的值是否在某些浮点范围内.问题是条件是按字母顺序检查的,而不是根据其浮点值.这是代码:

NSString * conditionToBeAdded = [NSString stringWithFormat:@" && (%@ >= \"""%@\""")  && (%@ <= \"""%@\""")", propertyName, myMinFloat, propertyName, myMaxFloat];
stringForPredicate = [stringForPredicate stringByAppendingString:conditionToBeAdded];  
NSPredicate * myPredicate = [NSPredicate predicateWithFormat:stringForPredicate];
Run Code Online (Sandbox Code Playgroud)

有人知道如何构建一个能够将字符串值检查为数字的NSPredicate对象,以便在coredata请求中使用吗?

谢谢.

小智 5

由于NSPredicates允许您使用与键值编码方法匹配的所有内容,因此可以调用NSStrings方法,如:intValue或floatValue

NSString * conditionToBeAdded = [NSString stringWithFormat:@" && (propertyName.floatValue >= %f )  && (propertyName.floatValue <= %f)", myMinFloat, myMaxFloat];
stringForPredicate = [stringForPredicate stringByAppendingString:conditionToBeAdded];  
NSPredicate * myPredicate = [NSPredicate predicateWithFormat:stringForPredicate];
Run Code Online (Sandbox Code Playgroud)

我希望有所帮助.

  • 此语法有效,但是结果仍然不正确。谓词:attribute01.intValue &lt;120不会返回包含“ 50”的字符串 (2认同)