有什么方法可以为 Objective-C 中的算术计算提供格式吗?
我想定义类似于计算方法的东西:
NSString *format = @"%d + 1";
在我的代码中我想做类似的事情:
int 计算编号 = sum(format,5) =>结果应该是 6。
你能给一些建议吗? 谢谢
编辑: 或类似的东西: NSNumber *no = [NSNumber numberWithFormat:format,5];
i want to define something similar to a computation method:
NSString *format = @"%d + 1";
In my code i want to do something like:
int computedNumber = sum(format,5) => the result should be 6.
could you give some suggestions?
thank you
EDIT:
or something similar to:
NSNumber *no = [NSNumber numberWithFormat:format,5];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这通常是不可能的,但是已经有针对此特定任务的书面解析器,值得一提的是 SO 的 DDMathParser用户戴夫·德隆。
但是您真正需要这个来完成什么任务呢?您有 + 运算符,然后执行 sum 函数?您不能简单地解析格式末尾的数字,然后执行您想要的操作吗?
It is not normally possible, however there have been written parsers for this specific tasks, to mention DDMathParser by SO user Dave DeLong.
But for what task do you really need this? You have the
+
operator, and then you perform thesum
function? Couldn't you simply parse the number at the end of the format, then perform the operation you'd like?使用
宏
可以是解决您的问题的另一种解决方案。您可以定义如下的宏
,这里,INC和a是用户定义的。您可以给它们起任何您想要的名称。无论您在哪里调用 INC(a),编译器都会在代码中替换 (a + 1)。例如,考虑以下情况,
编译后代码将是:
Using
Macro
can be an alternative solution to your problem. You can define amacro
like the following,Here, INC and a are user-defined. You can give them any name you want. Compiler will substitute (a + 1) in your code, where ever you call INC(a). For example, consider the following,
After the compilation the code will be,