此代码有效:
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来评估像那样的逻辑表达式?
感谢。
答案 0 :(得分:0)
使用NSPredicate代替NSExpression:
NSString* equation = @"2.5<=3";
NSPredicate* pre = [NSPredicate predicateWithFormat:equation];
BOOL result = [pre evaluateWithObject:nil];
NSLog(@"%@", (result ? @"YES" : @"NO"));