NSPredicate: how to treat strings as numbers?

有些话、适合烂在心里 提交于 2019-12-01 23:42:01

问题


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.


回答1:


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.




回答2:


You will want to change that string to a number and fix it properly. String searching is SLOW and should be avoided. Putting numbers into strings is a big performance hit with no gain.

As for your actual predicate, you can do a < or > comparison on strings. I suspect all of those quotation marks you have in the predicate are throwing things off. Quotation marks are not needed in predicates unless you are setting a constant which in this case you are not. Remove them and try it again.



来源:https://stackoverflow.com/questions/8879286/nspredicate-how-to-treat-strings-as-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!