NSPredicate:如何处理字符串作为数字? [英] NSPredicate: how to treat strings as numbers?

查看:286
本文介绍了NSPredicate:如何处理字符串作为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有没有人知道如何构建一个NSPredicate对象能够检查字符串值作为数字,

解决方案

由于NSPredicates允许你使用匹配Key-Value Coding方法的一切,你可以调用NSStrings方法,如:intValue或floatValue

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

我希望有帮助。


I am building a compound NSPredicate to make a fetch request, using core data on sqlite, within iOS app. Everything already works fine, but I am not being able to include the last condition. The reason is quite simple: I need to check if the value, stored as a string, is within certain float bounds. The problem is that the conditions are checked on alphabetical order basis, and not according its float value. Here it is the code:

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

Does anybody know how to build an NSPredicate object able to check string values as numbers, to be used within a coredata request?

Thank you.

解决方案

Since NSPredicates allow you to use everything which matches Key-Value Coding approach you can call on NSStrings methods like: intValue or floatValue

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

I hope that helps.

这篇关于NSPredicate:如何处理字符串作为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆