Search code examples
objective-cnsdecimalnumber

Simplify NSDecimalNumber initialisation


I have the following construct, which I would like to simplify. I had to use a NSString (?) in order to get rid of the NSNumber vs. NSDecimalNumber compiler Warning.

NSDecimalNumber *ticksSinceSeventies = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%d",[self timeIntervalSince1970]]];

Thanks for your Help!


Solution

  • If you are only using NSTimeIntervals, which are doubles, then the base 10 arithmetic that NSDecimalNumber affords you isn't really necessary. You can just use NSNumber instead.

    Your constructor would therefore just be:

    NSNumber *ticksSinceSeventies = [NSNumber numberWithDouble:[self timeIntervalSince1970]];
    

    (assuming self is an NSDate subclass, or this is inside a category method).