问题描述
我总是似乎遇到麻烦NSDecimalNumber!今天,我收到此错误:
I always seem to run into trouble with NSDecimalNumber! Today, I get this error:
是错误的根源:
- (void)setUpInstance {
static NSDecimalNumberHandler* roundingBehavior = nil;
if (roundingBehavior == nil) {
roundingBehavior = [[NSDecimalNumberHandler alloc] initWithRoundingMode:NSRoundDown scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
}
NSDecimalNumber *amount = viewController.aDecimalNumber;
NSDecimalNumber *actualValue = viewController.anotherDecimalNumber;
integralPortion = [amount decimalNumberByDividingBy:actualValue withBehavior:roundingBehavior];
...
}
文档将方法定义为:
-(NSDecimalNumber*)decimalNumberByDividingBy:(NSDecimalNumber *)decimalNumber
withBehavior:(id<NSDecimalNumberBehaviors>)behavior
我不能解释(id< NSDecimalNumberBehaviors>)行为
参数。这不是只是ANY对象,只要它符合NSDecimalNumbersBehaviors协议?
I must not be interpreting the "(id<NSDecimalNumberBehaviors>)behavior
" argument correctly. Isn't that just ANY object as long as it conforms to the NSDecimalNumbersBehaviors protocol?
我做错了什么?
星期五快乐!
推荐答案
这意味着你发送消息到一个纯NSNumber(NSCFNumber幕后)。您只能将其发送到NSDecimalNumber。
That means you're sending that message to a plain NSNumber (NSCFNumber behind the scenes). You can only send it to an NSDecimalNumber.
请注意,如何声明变量是不相关的。你可以声明 amount
为 NSString * amount
,你会得到完全相同的异常,包括NSCFNumber作为类名,因为它是一个异常,它发生在运行时。 (您当然也会收到关于NSString和NSDecimalNumber不可互换的编译时警告。)
Note that how you declare the variables is irrelevant. You could declare amount
as NSString *amount
and you would get the exact same exception, including NSCFNumber as the class name, because it is an exception, which happens at run-time. (You would, of course, also get the compile-time warning about NSString and NSDecimalNumber not being interchangeable.)
这篇关于麻烦与NSDecimalNumber的decimalNumberByDividingBy:withBehavior:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!