Logical NSExpression evaluation

931 Views Asked by At

This code works:

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

But this one doesn't, it ends up in a 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

Does anyone know if there's a way to use NSExpression to evaluate logical expressions like that one?

Thanks.

1

There are 1 best solutions below

0
On

Use NSPredicate instead of NSExpression:

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