Search code examples
objective-cios6operatorsnsexpression

Calculate lessthan value using NSExpression?


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"'


Solution

  • 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