NSExpression example

NSExpression is a very powerful class in iOS/OSX that calculate formula. We can also pass arguments or parameters to the formula:

NSExpression *expression1 = [NSExpression expressionWithFormat: @"1+2"];
NSLog(@"expression1 %@", [expression1 expressionValueWithObject:nil context:nil]);
NSExpression *expression2 = [NSExpression expressionWithFormat: @"1+%@-%@" argumentArray:@[@1.2, @2.2]];
NSLog(@"expression2 %@", [expression2 expressionValueWithObject:nil context:nil]);
NSMutableDictionary *context = [NSMutableDictionary dictionaryWithDictionary:
@{
@"offset": @1.3
}];
NSExpression *expression3 = [NSExpression expressionWithFormat: @"1+$offset*$offset+2.5"];
NSLog(@"expression3 %@", [expression3 expressionValueWithObject:nil context:context]);

The result will be:

expression1 3
expression2 0
expression3 5.19