Skip to content
Dave DeLong edited this page Aug 31, 2012 · 6 revisions

There are several ways to evaluate strings, depending on how much customization you want to do. Most of these options require an NSError ** parameter, although some do not.

  • If you use one of the options that does not accept an NSError **, then any tokenization, parsing, or evaluation errors will be NSLogged.
  • If you use one of the options that does accept an NSError **, then you must supply one. Failing to do so will probably result in a crash.

NSString

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

Useful for the simplest evaluations (ie, no variables). Uses the [DDMathEvaluator sharedMathEvaluator] and all functions registered with it.

NSString with substitutions

NSDictionary *s = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:42] forKey:@"a"];
NSLog(@"%@", [@"1 + $a" numberByEvaluatingStringWithSubstitutions:s]);

Also:

NSDictionary *s = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:42] forKey:@"a"];
NSError *error = nil;
NSLog(@"%@", [@"1 + $a" numberByEvaluatingStringWithSubstitutions:s error:&error]);

Useful for specifying variable substitutions. Uses the default [DDMathEvaluator sharedMathEvaluator].

DDExpression

NSError *error = nil;
DDExpression *e = [DDExpression expressionFromString:@"1 + 2" error:&error];
NSLog(@"%@", [e evaluateWithSubstitutions:nil evaluator:nil]);

Useful for specifying variable substitutions or a custom evaluator.

DDMathEvaluator *eval = [DDMathEvaluator sharedMathEvaluator];
NSLog(@"%@", [eval evaluateString:@"1 + 2" withSubstitutions:nil]);

Useful for specifying variable substitutions, a custom evaluator, or changing the angle measurement mode.

NSError *error = nil;
DDParser *parser = [DDParser parserWithString:@"1 + 2" error:&error];
DDExpression *e = [parser parsedExpressionWithError:&error];
NSLog(@"%@", [e evaluateWithSubstitutions:nil evaluator:nil error:&error]);

Useful for specifying a custom parser, specifying variables, specifying a custom evaluator, or changing the angle measurement mode.

NSError *error = nil;
DDMathStringTokenizer *t = [DDMathStringTokenizer tokenizerWithString:@"1 + 2" error:&error];
DDParser *parser = [DDParser parserWithTokenizer:t error:&error];
DDExpression *e = [parser parsedExpressionWithError:&error];
NSLog(@"%@", [e evaluateWithSubstitutions:nil evaluator:nil error:&error]);

Useful for specifying a custom tokenizer or custom operator associativities.