问题
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!
回答1:
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.
回答2:
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)"];
来源:https://stackoverflow.com/questions/29061407/how-to-use-modulus-operator-with-nsexpression