逻辑NSExpression评估

时间:2014-01-24 10:25:33

标签: ios objective-c nsexpression

此代码有效:

NSString* equation = @"2.5*3";
NSExpression* expresion = [NSExpression expressionWithFormat:equation, nil];
NSNumber* result = [expresion expressionValueWithObject:nil context:nil];
NSLog(@"%@", result); // 7.5

但是这个没有,它最终以NSInvalidArgumentException

结束
NSString* equation = @"2.5<=3";
NSExpression* expresion = [NSExpression expressionWithFormat:equation, nil];
NSNumber* result = [expresion expressionValueWithObject:nil context:nil];
NSLog(@"%@", result); //I wanted result to be 1, as the expression is true

有没有人知道是否有办法使用NSExpression来评估像那样的逻辑表达式?

感谢。

1 个答案:

答案 0 :(得分:0)

使用NSPredicate代替NSExpression:

NSString* equation = @"2.5<=3";
NSPredicate* pre = [NSPredicate predicateWithFormat:equation];
BOOL result = [pre evaluateWithObject:nil];
NSLog(@"%@", (result ? @"YES" : @"NO"));