[英]Is there any way to give a format to arithmetic computations in Objective-C?
i want to define something similar to a computation method: 我想定义类似于计算方法的内容:
NSString *format = @"%d + 1";
NSString * format = @“%d + 1”;
In my code i want to do something like: 在我的代码中,我想做类似的事情:
int computedNumber = sum(format,5) => the result should be 6.
int computeNumber = sum(format,5)=>结果应为6。
could you give some suggestions? 你能给点建议吗? thank you
谢谢
EDIT: or something similar to: NSNumber *no = [NSNumber numberWithFormat:format,5]; 编辑:或类似于以下内容:NSNumber * no = [NSNumber numberWithFormat:format,5];
It is not normally possible, however there have been written parsers for this specific tasks, to mention DDMathParser by SO user Dave DeLong . 通常不可能,但是已经为该特定任务编写了解析器,SO用户Dave DeLong提到了DDMathParser 。
But for what task do you really need this? 但是您真的需要什么呢? You have the
+
operator, and then you perform the sum
function? 您有
+
运算符,然后执行sum
功能? Couldn't you simply parse the number at the end of the format, then perform the operation you'd like? 您不能简单地解析格式末尾的数字,然后执行所需的操作吗?
Using Macro
can be an alternative solution to your problem. 使用
Macro
可以解决您的问题。 You can define a macro
like the following, 您可以定义如下的
macro
,
#define INC(a) (a + 1)
Here, INC and a are user-defined. 在此, INC和a是用户定义的。 You can give them any name you want.
您可以给他们想要的任何名称。 Compiler will substitute (a + 1) in your code, where ever you call INC(a) .
无论您在哪里调用INC(a) ,编译器都会在您的代码中替换(a +1 ) 。 For example, consider the following,
例如,考虑以下情况,
int computedNumber = INC(5);
After the compilation the code will be, 编译后的代码将是
int computedNumber = (5 + 1); // the result during the execution is 6.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.