Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it okay to use primitive data types?

It seems like Apple encourages the use of their classes, e.g. NSNumber, rather than the primitive C types like int and float, but sometimes it seems like overkill. When do you recommend using the latter over the former?

like image 255
wumbo Avatar asked Feb 01 '26 21:02

wumbo


2 Answers

When to use primitive

If you need to de work with your numbers (do math, modify the value...) then you should be using primitives, I prefer the Cocoa typedef's (NSInteger, CGFloat) but you might need to do specific things and have larger numbers with long long or something...

So it's up to your preferences and the use case.

About NSNumber

NSNumber is a subclass of NSValue, this is useful when you need to work with objects like in APIs or even just working with containers like NSArray or NSDictionary.

Thus NSNumber is just a container for a primitive.

If you look at the documentation for NSNumber you'll see a whole bunch of methods to create an object from each primitive type, and a bunch of methods to extract a primitive value from the object. There are a couple of compare methods and helpful methods to get string representations also. But what you'll notice is it's really only an object container for a primitive.

like image 134
Daniel Avatar answered Feb 03 '26 12:02

Daniel


Any answer to this question is going to be a mix of fact and opinion...

The question really should be the other way around - when should you use object wrappers instead of primitive values? Apple certainly does not encourage the use of NSNumber over primitive types unless there is a need.

Two reasons to use NSNumber:

  1. You need an object, e.g. you need to store the primitive value (on its own, not as part of another object) in an object-based collection such as NSArray.
  2. You need a "nullable" type, i.e. a type which is either represents a primitive value or the absence of such a value - often used in databases. Note that in this case defining and using your own value-based struct for your nullable primitive type might be a better option, or not, depending on the situation. (MS's .NET framework uses value-based nullable primitives while also having object-based primitive wrappers.)

Reasons you may want to avoid NSNumber:

  1. It is more expensive - this isn't a case of premature optimisation, but of not using avoiding that as an excuse to write intentionally bad code!
  2. It is immutable - if you're doing even a modest amount of math this will probably be a pain.

Remember types such as NSInteger, CGFloat etc. are not object types, just convenient typedef's for language primitive types; and the framework APIs are full of uses of these types. Maybe unfortunately Apple never adopted a naming convention to distinguish between framework value types and object types.

HTH.

like image 32
CRD Avatar answered Feb 03 '26 10:02

CRD