How to use modulus operator with NSExpression?

爷,独闯天下 提交于 2019-12-11 11:13:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!