Add dynamic rating to obj-c

I know that Obj-c is a compiled language and does not offer any eval functionality such as python or ruby, but I need some dynamic functionality, and I cannot decide between two different approaches.

Problem: You have a line describing a complex mathematical formula, for example

@"var_a + 4 - (3 * var_b)"

I already have a way to evaluate the current value from var_aand var_b, so the first step is fine. The second step is to evaluate the formula, and we have at least two different options:

  • Create a line and try evaluating with the javascript engine (a very bad idea).
  • The map in obj-c objects is the main idea of ​​the matematica formula. I am talking about creating an object in an example SUM_Objectthat takes two different operands and returns the sum of two parameters (and so on ... for example, separation, etc.).
  • Use DDMathParser.

I think point number 2 is the best solution ... any advice?

thank.

+4
source share
2 answers

Why not use NSExpression? http://nshipster.com/nsexpression/

UPDATE:

You will need something like this

int a = 1, b = 2;
NSExpression *expression = [NSExpression expressionWithFormat:@"%i + 4 - (3 * %i)", a, b];
id value = [expression expressionValueWithObject:nil context:nil];

UPDATE2:

Unable to use <, >, ==, !=, >=, <=in NSExpression. But you can use NSPredicate

int a = 1, b = 2;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%i > %i", a, b];
BOOL result = [predicate evaluateWithObject:nil];
+2
source

/ , DDMathParser. .

Wiki:

NSLog(@"%@", [@"1 + 2" numberByEvaluatingString]);

:

, .

+1

Source: https://habr.com/ru/post/1528855/


All Articles