如何添加两个NSNumber对象

如何添加两个NSNumber对象

本文介绍了如何添加两个NSNumber对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在这必须很容易,但是如何将两个NSNumber相加?就像:

Now this must be easy, but how can sum two NSNumber? Is like:

[one floatValue] + [two floatValue]

还是存在更好的方法?

推荐答案

确实没有更好的方法,但是如果可以避免的话,您实际上不应该这样做. NSNumber作为标量数字的包装器而存在,因此您可以将它们存储在集合中,并与其他NSObjects多态传递.它们并没有真正用于在实际数学中存储数字.如果对它们进行数学运算,则比仅对标量执行运算要慢得多,这可能就是为什么没有便捷方法的原因.

There is not really a better way, but you really should not be doing this if you can avoid it. NSNumber exists as a wrapper to scalar numbers so you can store them in collections and pass them polymorphically with other NSObjects. They are not really used to store numbers in actual math. If you do math on them it is much slower than performing the operation on just the scalars, which is probably why there are no convenience methods for it.

例如:

NSNumber *sum = [NSNumber numberWithFloat:([one floatValue] + [two floatValue])];

在消息分发上至少要吹21条指令,但是该方法需要花费很多代码才能对取消装箱并重新装箱值(可能是几百个)来完成1条指令的数学运算.

Is blowing at a minimum 21 instructions on message dispatches, and however much code the methods take to unbox the and rebox the values (probably a few hundred) to do 1 instruction worth of math.

因此,如果您需要将数字存储在字典中,请使用NSNumber,如果您需要将可能是数字或字符串的内容传递给函数,请使用NSNumber,但是如果您只是想做数学运算,标量C类型.

So if you need to store numbers in dicts use an NSNumber, if you need to pass something that might be a number or string into a function use an NSNumber, but if you just want to do math stick with scalar C types.

这篇关于如何添加两个NSNumber对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:25