objective-c 如何添加两个 NSNumber 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/494002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add two NSNumber objects?
提问by mamcx
Now this must be easy, but how can sum two NSNumber? Is like:
现在这一定很容易,但是如何将两个相加NSNumber呢?就好像:
[one floatValue] + [two floatValue]
or exist a better way?
或者存在更好的方法?
回答by Louis Gerbarg
There is not really a better way, but you really should not be doing this if you can avoid it. NSNumberexists 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作为标量数字的包装器存在,因此您可以将它们存储在集合中并与其他NSObjects. 它们并没有真正用于在实际数学中存储数字。如果对它们进行数学运算,它比仅对标量执行运算要慢得多,这可能就是为什么没有方便的方法的原因。
For example:
例如:
NSNumber *sum = [NSNumber numberWithFloat:([one floatValue] + [two floatValue])];
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.
在消息调度上至少有 21 条指令,无论这些方法需要多少代码来取消装箱和重新装箱值(可能是几百个)以进行 1 条指令的数学运算。
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.
因此,如果您需要在 dicts 中存储数字,请使用 an NSNumber,如果您需要将可能是数字或字符串的内容传递给函数,请使用 an NSNumber,但如果您只想使用标量 C 类型进行数学运算。
回答by Semmel
NSDecimalNumber(subclass of NSNumber) has all the goodies you are looking for:
NSDecimalNumber(NSNumber 的子类)拥有您正在寻找的所有好东西:
– decimalNumberByAdding:
– decimalNumberBySubtracting:
– decimalNumberByMultiplyingBy:
– decimalNumberByDividingBy:
– decimalNumberByRaisingToPower:
...
...
If computing performance is of interest, then convert to C++ array std::vector or like.
如果对计算性能感兴趣,则转换为 C++ 数组 std::vector 等。
Now I never use C-Arrays anymore; it is too easy to crash using a wrong index or pointer. And very tedious to pair every new [] with delete[].
现在我不再使用 C 数组了;使用错误的索引或指针很容易崩溃。将每个新的 [] 与删除 [] 配对非常乏味。
回答by nemesis
You can use
您可以使用
NSNumber *sum = @([first integerValue] + [second integerValue]);
Edit:
As observed by ohho, this example is for adding up two NSNumberinstances that hold integer values. If you want to add up two NSNumber's that hold floating-point values, you should do the following:
编辑:正如ohho所观察到的那样,此示例用于将两个NSNumber包含整数值的实例相加。如果要将两个NSNumber包含浮点值的 's相加,则应执行以下操作:
NSNumber *sum = @([first floatValue] + [second floatValue]);
回答by Dan Loewenherz
The current top-voted answeris going to lead to hard-to-diagnose bugs and loss of precision due to the use of floats. If you're doing number operations on NSNumber values, you should convert to NSDecimalNumber first and perform operations with those objects instead.
由于使用浮点数,当前最高投票的答案将导致难以诊断的错误和精度损失。如果您正在对 NSNumber 值进行数字操作,您应该首先转换为 NSDecimalNumber 并使用这些对象执行操作。
From the documentation:
从文档:
NSDecimalNumber, an immutable subclass of NSNumber, provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.
NSDecimalNumber 是 NSNumber 的不可变子类,它提供了一个面向对象的包装器,用于执行 base-10 算术。一个实例可以表示任何可以表示为尾数 x 10^指数的数字,其中尾数是最多 38 位的十进制整数,指数是从 –128 到 127 的整数。
Therefore, you should convert your NSNumber instances to NSDecimalNumbers by way of [NSNumber decimalValue], perform whatever arithmetic you want to, then assign back to an NSNumber when you're done.
因此,您应该通过 将您的 NSNumber 实例转换为 NSDecimalNumbers [NSNumber decimalValue],执行您想要的任何算术,然后在完成后分配回 NSNumber。
In Objective-C:
在 Objective-C 中:
NSDecimalNumber *a = [NSDecimalNumber decimalNumberWithDecimal:one.decimalValue]
NSDecimalNumber *b = [NSDecimalNumber decimalNumberWithDecimal:two.decimalValue]
NSNumber *result = [a decimalNumberByAdding:b]
In Swift 3:
在 Swift 3 中:
let a = NSDecimalNumber(decimal: one.decimalValue)
let b = NSDecimalNumber(decimal: two.decimalValue)
let result: NSNumber = a.adding(b)
回答by Motti Shneor
Why not use NSxEpression?
为什么不使用NSxEpression?
NSNumber *x = @(4.5), *y = @(-2);
NSExpression *ex = [NSExpression expressionWithFormat:@"(%@ + %@)", x, y];
NSNumber *result = [ex expressionValueWithObject:nil context:nil];
NSLog(@"%@",result); // will print out "2.5"
You can also build an NSExpression that can be reused to evaluate with different arguments, like this:
您还可以构建一个 NSExpression,可以重用它来评估不同的参数,如下所示:
NSExpression *expr = [NSExpression expressionWithFormat: @"(X+Y)"];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:x, @"X", y, @"Y", nil];
NSLog(@"%@", [expr expressionValueWithObject:parameters context:nil]);
For instance, we can loop evaluating the same parsed expression, each time with a different "Y" value:
例如,我们可以循环评估相同的解析表达式,每次使用不同的“Y”值:
for (float f=20; f<30; f+=2.0) {
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:x, @"X", @(f), @"Y", nil];
NSLog(@"%@", [expr expressionValueWithObject:parameters context:nil]);
}
回答by William Falcon
In Swift you can get this functionality by using the Bolt_Swift library https://github.com/williamFalcon/Bolt_Swift.
在 Swift 中,您可以通过使用 Bolt_Swift 库https://github.com/williamFalcon/Bolt_Swift来获得此功能。
Example:
例子:
var num1 = NSNumber(integer: 20)
var num2 = NSNumber(integer: 25)
print(num1+num2) //prints 45

![objective-c UIViewController [Xcode 5] 中的静态表视图](/res/img/loading.gif)