What is the use of NSExpression?

后端 未结 4 1872
野趣味
野趣味 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:43

    NSExpression is not a general-purpose mathematical expression evaluator. It's meant to be used with NSPredicate to describe selection criteria in Core Data queries.

    0 讨论(0)
  • 2021-01-03 13:46

    NSExpression is used to represent expressions in NSPredicate. It is not intended for the tasks like yours.

    Actually, you can use NSExpression to calculate the formula value, but this usage is quite limited. To evaluate any mathematical expression you would need to make a string parser using some algorithm i.e. Shunting-yard or just reuse a library like this one.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-03 13:59

    NSExpression is useful for evaluating math expressions in objective c.

    let's see how to find the standard deviation of numbers using NSExpression

    NSArray *arrNumbers = @[@3, @6, @3, @8, @4, @12, @9, @11];
    
    NSExpression *expression = [NSExpression expressionForFunction:@"stddev:" arguments:@[[NSExpression expressionForConstantValue:arrNumbers]]];
    
    id value = [expression expressionValueWithObject:nil context:nil];
    

    It's that simple.

    Below is list of functions grouped by category.

    1)List of statistics methods

    average:
    sum:
    count:
    min:
    max:
    median:
    mode:
    stddev:
    

    2)Arithmetic functions

    add:to:
    from:subtract:
    multiply:by:
    divide:by:
    modulus:by:
    abs:
    sqrt:
    log:
    ln:
    raise:toPower:
    exp:
    

    3)Bounding functions

    ceiling:
    trunc: 
    

    4)Random functions

    random
    random:
    

    5)Binary arithmetic functions

    bitwiseAnd:with:
    bitwiseOr:with:
    bitwiseXor:with:
    leftshift:by:
    rightshift:by:
    onesComplement:
    

    6)Date functions

    now
    

    7)String functions

    lowercase:
    uppercase:
    

    8)No-Op

    noindex:
    
    0 讨论(0)
提交回复
热议问题