我想做的是遍历我的核心数据对象并添加每件商品的价格并返回总计。我的以下代码不断崩溃,我不知道为什么。以前我使用的是 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/