1

how to use modulus operator with NSExpression? If i use

NSExpression *exp = [NSExpression expressionWithFormat:@"3%2"];

I'm getting an error — *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "3%2 == 1"'.

Can anyone explain how to correctly use modulus operator with NSExpression? An example would be great!

Monis Manzoor
  • 183
  • 3
  • 14

2 Answers2

0

NSExpression has a function feature for mathematic equations like the modulus. Here is an example of how you would perform the equation you asked:

NSExpression *expression = [NSExpression expressionForFunction:@"modulus:by:" arguments:@[[NSExpression expressionForConstantValue:@3], [NSExpression expressionForConstantValue:@2]]];

id value = [expression expressionValueWithObject:nil context:nil];

NSLog(@"%@", value); // Output is 1

Here is a link to a StackOverflow post that contains multiple lists of the functions you can use with NSExpression.

Community
  • 1
  • 1
SierraMike
  • 1,539
  • 1
  • 11
  • 18
0

You can use +[NSExpression expressionForFunction:arguments:], as @Sean McDonald suggests, or if you find that too verbose, you can use the syntax for a predefined function in a format string:

NSExpression *exp = [NSExpression expressionWithFormat:@"modulus:by:(3, 2)"];
Minh Nguyễn
  • 861
  • 7
  • 18