views:

567

answers:

1

So I am trying to do a few things with numbers in Objective C and realize there is a plethora of options, and i am just bewildered as to which type to use for my app.

so here are the types.

  • NSNumber (which is a class)
  • NSDecmial (which is a struct)
  • NSDecimalNumber (which is a class)
  • float/double (which are primitive types)

so essentially what i need to do is take an NSString, which is representing decimal based hours. (10.4 would be 10 hours and (4/10)*60 minutes) and convert it into:

  1. a string representation D H:M (this needs division, multiplication and basic arithmatic)
  2. a Number type to store for easy calculations latter (will mostly be converting between NSTimeIntervals and doing subtractions)

Oh and i need to be able to do an Absolute value as well on these

It appears that the hard part is actually transitioning between the types.

To me this is a very trivial problem so I"m not sure if its getting late or because objective C numerical types suck, but i could use a hand.

+3  A: 

Use primitive types (double, CGFLoat, NSInteger) for typical arithmetic and when you need to store a number as an instance variable that's going to be used primarily for arithmetic in other places. You can use C math functions (abs(), pow(), etc) as needed. NSTimeInterval is a typedef for double, so you can interchange the two.

Use NSNumber when you need to store a number as an object, for example if you're creating an NSArray of numbers. Some parts of Cocoa like Core Data or key value coding deal more with NSNumber than primitive types, so you may find yourself using NSNumber more then usual in those situations. For example, if you write [timeKeepersArray valueForKeyPath:@"sum.seconds"] you'll get back an NSNumber, so you may find it easier just to keep that variable instead of converting it to a primitive.

Since it's a small amount of extra code to convert between NSNumber and primitive types, usually your application will end up favoring one or the other depending on what you're doing with numbers.

Oh, and NSDecmial and NSDecimalNumber? Don't worry too much about them, they only come up when you need really precise decimal operations, such as if you're storing financial data.

Marc Charbonneau