4

I know Obj-c is a compiled language and doesn't offers any eval funcionality like python or ruby, but i need some dynamics functinality and i cannot decide between two different approac.

The problem: You have a string that describe a complex math formula, like

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

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

  1. Create a string and try to evaluate with javascript engine (very bad idea).
  2. Map in objects obj-c the basic idea of formula matematica. I'm talking about create at example an object SUM_Object that accept two different operand and return the sum of the two parameters (and so on...like division etc).
  3. Use DDMathParser.

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

thanks.

IgnazioC
  • 4,554
  • 4
  • 33
  • 46

2 Answers2

2

Why not to 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:

It is impossible to use <, >, ==, !=, >=, <= in NSExpression. But you could use NSPredicate

int a = 1, b = 2;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%i > %i", a, b];
BOOL result = [predicate evaluateWithObject:nil];
Avt
  • 16,927
  • 4
  • 52
  • 72
  • 1
    An alternative method to substitute variables is described here: http://stackoverflow.com/a/12994596/1187415. NSExpression has also some disadvantages, for example `1/3` evaluates to zero because it does integer division if both operands are integers. Actually I would use a proper math parser (like DDMathParser) for all non-trivial tasks. – Martin R Feb 25 '14 at 23:03
  • Depends on formulas complexity. There is no sense to include additional third party library if all you need is `@"var_a + 4 - (3 * var_b)"`. – Avt Feb 25 '14 at 23:11
  • Do NSExpression have some boolean capability? Like `<`,`>`,`<=` et simila? – IgnazioC Feb 26 '14 at 07:05
1

If you need to parse/evaluate advanced math expressions have a look at DDMathParser. It let's you also add your own expressions easily.

Example from the Wiki:

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

Update:

As you can see on the Operators page in the wiki of the project, it supports also logic operators.

Sandro Meier
  • 3,071
  • 2
  • 32
  • 47