Search code examples
iosobjective-cnsdecimalnumbernsdecimal

Set NSDecimal to zero


What are the different ways of setting a NSDecimal to zero? I'm not keen on any of the 3 I found so far.

NSDecimal zero = {0}; // Not obvious what's going on here.

NSDecimal zero = @(0).decimalValue; // @(0) appears to always return the same instance.

NSDecimal zero = [NSDecimalNumber zero].decimalValue; // [NSDecimalNumber zero] appears to always return the same instance.

Is there one that is most accepted than others? Am I missing some kind of NSDecimalZero constant/function?


Solution

  • I have never noticed that NSDecimal doesn't have a nice Create function.

    I can't imagine another method than the 3 you list.

    NSDecimal zero = {0};
    

    You are right, this is not obvious, this is actually very far from obvious. Usual programmers won't look up the documentation to see what value the struct will represent with all attributes set to zero.

    NSDecimal zero = @(0).decimalValue
    

    I don't like it because it uses NSNumber and needlessly creates an autoreleased object.

    NSDecimal zero = [NSDecimalNumber zero].decimalValue
    

    This is my preferred solution. Using NSDecimal structs directly is done mostly for performance boosts (without creating objects on the heap). This method matches the intent because it uses a singleton constant.

    However, if you have a lot of code involving NSDecimal and performance is really important for you, create your own function/macro to initialize the struct and use this function everywhere. Then this problem won't matter to you because the function name will make the code obvious.