How do you use different types of numbers in Objective C

So I'm trying to do a few things with numbers in Objective C and I realize there are many options and I'm just confused about which type to use for my application.

so here are the types.

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

so essentially I need to make an NSString that represents the decimal hours. (10.4 would be 10 hours and (4/10) * 60 minutes) and convert it to:

  • string representation DH: M (this requires division, multiplication, and basic arithmetic)
  • Type of number to store for easy computations of the latter (will mainly convert between NSTimeIntervals and do subtractions)

Oh, and I also need to be Absolute on these

It looks like the hard part is actually switching between types.

For me this is a very trivial problem, so I'm not sure if its late or because of objective C-numerical types to suck, but I could use my hand.

+1


a source to share


1 answer


Use primitive types (double, CGFLoat, NSInteger) for typical arithmetic and when you need to store a number as an instance variable that will be used mainly for arithmetic elsewhere. You can use C math functions (abs (), pow (), etc.) as needed. NSTimeInterval is a typedef for double, so you can swap the two.

Use NSNumber when you need to store a number as an object, for example if you are creating an NSArray of numbers. Some parts of Cocoa, such as Core Data or key value, code more with NSNumber than primitive types, so you might find yourself in NSNumber more common in these situations. For example, if you write [timeKeepersArray valueForKeyPath:@"sum.seconds"]

, you will get an NSNumber, so it might be easier for you to just store that variable instead of converting it to a primitive.



Since this is a small amount of extra code to convert between NSNumber and primitive types, usually your application will favor one or the other depending on what you do with the numbers.

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

+5


a source







All Articles