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.
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