ios - 如何将核心数据中每个对象的小数值相加得出总数?

标签 ios objective-c cocoa-touch core-data nsdecimalnumber

我想做的是遍历我的核心数据对象并添加每件商品的价格并返回总计。我的以下代码不断崩溃,我不知道为什么。以前我使用的是 float ,但有人建议我改用 NSDecimalNumber,因为它更准确。所以我着手转换我的代码以使用它。

循环遍历对象并添加价格然后返回总计的代码:

+ (NSDecimalNumber *)totalPriceOfItems:(NSManagedObjectContext *)managedObjectContext
{
    NSError *error = nil;
    NSDecimalNumber *totalPrice = [[NSDecimalNumber alloc] init];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"BagItem"];

    // Get fetched objects and store in NSArray
    NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

    for (BagItem *bagItem in fetchedObjects) {

     //   NSDecimalNumber *price = [NSDecimalNumber decimalNumberWithString:[bagItem price]];
      //  NSString *price = [[[bagItem price] componentsSeparatedByCharactersInSet:
          //                  [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
            //               componentsJoinedByString:@""];
       totalPrice = [totalPrice decimalNumberByAdding:[bagItem price]];

        NSLog(@"total: %@", totalPrice);
    }

    return totalPrice;
}

错误:

** Terminating app due to uncaught exception 'NSDecimalNumberOverflowException', reason: 'NSDecimalNumber overflow exception'
*** First throw call stack:

最佳答案

你得到的异常是因为你试图添加两个非常大的数字并且表示它所需的位数对于 NSDecimalNumber 来说太大了。您的数字可能不是问题所在,问题在于您声明 totalPrice 变量的方式。

这一行应该改一下

NSDecimalNumber *totalPrice = [[NSDecimalNumber alloc] init];

NSDecimalNumber *totalPrice = [NSDecimalNumber zero];

NSDecimalNumber 是 NSDecimal 的包装器(它本身是 NSValue 的包装器)并且不为其 init 方法提供默认值。如果它做了,值(value)应该是多少?一、零、十万?它实际上默认为 NaN。本质上,您的起始值可能会占用所有可用字节,并且每当您添加到它时都会出现异常。

NSDecimalNumber 具有内置机制来处理诸如溢出和其他数学错误(例如被零除)之类的事情。您可以通过调用 setBehavior 方法提供新的行为对象来更改默认行为。

关于ios - 如何将核心数据中每个对象的小数值相加得出总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24600801/

相关文章:

ios - 如何检查 UISegmentedControl 特定段是否已启用?

iphone - 将UITableView变成UIImageView

ios - iPad 应用程序中的旋转

ios - UIButton _setTitleFrozen 崩溃

ios - iPhone - 如何从一组 UILabel 中进行选择?

ios - 如何在 Swift 中的自定义类中初始化 Timer?

ios - 使用导航显示 map View ?.push(mapView) 并且看不到任何弹出内容

iOS - GitHub Firebase 身份验证

iphone - setDefaultCredential 不适用于 iOS 7 中的 UIWebView,但在早期的 iO​​S 版本中工作正常

iphone - 过早退出 dispatch_async ,Grand Central Dispatch