简体   繁体   English

有什么办法可以给Objective-C中的算术计算提供格式?

[英]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. 在此, INCa是用户定义的。 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.

相关问题 有没有办法在C中使用Objective-C库? - is there any way to use Objective-C library in C? 如何在Objective-C中更改日期格式 - how to change the date format in the objective-c 在Objective-C中设置日期格式 - Setting date format in Objective-C Objective-C有检测AirPlay的通知吗? - Is there any notification for detecting AirPlay in Objective-C? Objective-C,有什么方法可以使用MPMoviePlayerController和AVAssetImageGenerator从URL提取视频缩略图吗? - Objective-c, Is there any way fetch video thumbnail from URL instead using MPMoviePlayerController and AVAssetImageGenerator? 使用UIWebView时,有没有办法从Objective-C访问DOM? - Is there any way to get access to the DOM from Objective-C when using UIWebView? 使用Objective-C,有没有办法比较两个图像并返回%差值? - Using Objective-C, is there any way to compare two images and get a % difference value returned? 如何使用NSRegularExpression或Objective-C中的任何其他有效方法检查GUID(或UUID)的有效性 - How to check the validity of a GUID (or UUID) using NSRegularExpression or any other effective way in Objective-C 以安全的方式共享代码Objective-C - Share the code in a secure way Objective-C 在 Objective-C 中随机化 NSArray 的规范方法 - canonical way to randomize an NSArray in Objective-C
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM