如何添加两个 NSNumber 对象?

发布于 2024-07-13 02:58:28 字数 138 浏览 8 评论 0原文

现在这一定很简单,但是如何对两个 NSNumber 求和呢? 就像:

[one floatValue] + [two floatValue]

或者存在更好的方式吗?

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

[one floatValue] + [two floatValue]

or exist a better way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

我是有多爱你 2024-07-20 02:58:29

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

例如:

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

在消息调度上至少需要 21 条指令,无论这些方法需要多少代码来对值进行拆箱和重新装箱(可能是几百个)才能完成 1 条指令的数学运算。

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

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.

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.

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.

注定孤独终老 2024-07-20 02:58:29

NSDecimalNumberNSNumber) 拥有您正在寻找的所有好东西:

– decimalNumberByAdding:
– decimalNumberBySubtracting:
– decimalNumberByMultiplyingBy:
– decimalNumberByDividingBy:
– decimalNumberByRaisingToPower:

...

如果对计算性能感兴趣,则转换为 C++ 数组 std::vector 或类似的。

现在我不再使用 C 数组了; 使用错误的索引或指针很容易崩溃。 将每个新的 [] 与删除 [] 配对非常繁琐。

NSDecimalNumber (subclass of NSNumber) has all the goodies you are looking for:

– decimalNumberByAdding:
– decimalNumberBySubtracting:
– decimalNumberByMultiplyingBy:
– decimalNumberByDividingBy:
– decimalNumberByRaisingToPower:

...

If computing performance is of interest, then convert to C++ array std::vector or like.

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[].

jJeQQOZ5 2024-07-20 02:58:29

您可以使用

NSNumber *sum = @([first integerValue] + [second integerValue]);

编辑:
正如 ohho 所观察到的,此示例用于将两个保存整数值的 NSNumber 实例相加。 如果您想将两个保存浮点值的 NSNumber 相加,您应该执行以下操作:

NSNumber *sum = @([first floatValue] + [second floatValue]);

You can use

NSNumber *sum = @([first integerValue] + [second integerValue]);

Edit:
As observed by ohho, this example is for adding up two NSNumber instances that hold integer values. If you want to add up two NSNumber's that hold floating-point values, you should do the following:

NSNumber *sum = @([first floatValue] + [second floatValue]);
触ぅ动初心 2024-07-20 02:58:29

当前的得票最高的答案将导致难以诊断的错误和由于使用漂浮。 如果您要对 NSNumber 值进行数字运算,则应首先转换为 NSDecimalNumber,然后对这些对象执行运算。

来自文档

NSDecimalNumber 是 NSNumber 的不可变子类,它提供了一个面向对象的包装器来执行以 10 为基数的算术。 实例可以表示任何可以表示为尾数 x 10^指数的数字,其中尾数是最多 38 位的十进制整数,指数是从 –128 到 127 的整数。

因此,您应该将 NSNumber 实例转换为 NSDecimalNumbers [NSNumber十进制值]的方式,执行你想要的任何算术,然后在完成后分配回一个NSNumber。

在 Objective-C 中:

NSDecimalNumber *a = [NSDecimalNumber decimalNumberWithDecimal:one.decimalValue]
NSDecimalNumber *b = [NSDecimalNumber decimalNumberWithDecimal:two.decimalValue]
NSNumber *result = [a decimalNumberByAdding:b]

在 Swift 3 中:

let a = NSDecimalNumber(decimal: one.decimalValue)
let b = NSDecimalNumber(decimal: two.decimalValue)
let result: NSNumber = a.adding(b)

The current top-voted answer is 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.

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.

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.

In Objective-C:

NSDecimalNumber *a = [NSDecimalNumber decimalNumberWithDecimal:one.decimalValue]
NSDecimalNumber *b = [NSDecimalNumber decimalNumberWithDecimal:two.decimalValue]
NSNumber *result = [a decimalNumberByAdding:b]

In Swift 3:

let a = NSDecimalNumber(decimal: one.decimalValue)
let b = NSDecimalNumber(decimal: two.decimalValue)
let result: NSNumber = a.adding(b)
痴梦一场 2024-07-20 02:58:29

为什么不使用 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"

您还可以构建一个 NSExpression,它可以重复用于使用不同的参数进行计算,如下所示:

NSExpression *expr = [NSExpression expressionWithFormat: @"(X+Y)"];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:x, @"X", y, @"Y", nil];
NSLog(@"%@", [expr expressionValueWithObject:parameters context:nil]);

例如,我们可以循环计算相同的解析表达式,每次使用不同的“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]);
 }

Why not use 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 *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:

 for (float f=20; f<30; f+=2.0) {
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:x, @"X", @(f), @"Y", nil];
    NSLog(@"%@", [expr expressionValueWithObject:parameters context:nil]);
 }
菊凝晚露 2024-07-20 02:58:29

在 Swift 中,您可以使用 Bolt_Swift 库 https://github.com/williamFalcon/Bolt_Swift 获得此功能。

例子:

  var num1 = NSNumber(integer: 20)
  var num2 = NSNumber(integer: 25)
  print(num1+num2) //prints 45

In Swift you can get this functionality by using the Bolt_Swift library https://github.com/williamFalcon/Bolt_Swift.

Example:

  var num1 = NSNumber(integer: 20)
  var num2 = NSNumber(integer: 25)
  print(num1+num2) //prints 45
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文