如何添加两个 NSNumber 对象? [英] How to add two NSNumber objects?

查看:23
本文介绍了如何添加两个 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 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆