Calculate lessthan value using NSExpression?

混江龙づ霸主 提交于 2019-12-29 09:33:26

问题


For the following block of code:

NSString *formul=@"5 < 9";

NSExpression *e = [NSExpression expressionWithFormat:formul];

int result = [[e expressionValueWithObject:nil context:nil] intValue];

NSLog(@"formule:%d", result);

I got error:

due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "5 < 9 == 1"'


回答1:


You can use NSPredicate instead:

NSString *formul = @"15 < 9";
NSPredicate *predicate = [NSPredicate predicateWithFormat:formul];
BOOL b = [predicate evaluateWithObject:nil];

In Swift:

let formula = "15 < 9"
let predicate = NSPredicate(format: formula)
let b = predicate.evaluate(with: nil)
print(b) // false


来源:https://stackoverflow.com/questions/18871071/calculate-lessthan-value-using-nsexpression

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