What is the use of NSExpression?

后端 未结 4 1892
野趣味
野趣味 2021-01-03 13:23

How to calculate formulas like (a + b) ^ 2, sum((a + b) / 2) using NSExpression? I am the beginner to NSExpression.

(a + b) ^

4条回答
  •  既然无缘
    2021-01-03 13:55

    NSExpression is great for evaluating mathematical expressions. It is NOT only limited to core data queries and you DO NOT need additional third party libraries or write your own parser to evaluate expressions as strings.

    To actually answer the question for (a + b) ^ 2 ;)

    NSNumber *a = @4;
    NSNumber *b = @4;
    NSExpression *expression = [NSExpression expressionWithFormat:@"(%@ + %@)**2", a, b];
    NSNumber *result = [expression expressionValueWithObject:nil context:nil];
    NSLog(@"%@",result);
    

提交回复
热议问题