Reputation: 746
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?
Upvotes: 2
Views: 178
Reputation: 23359
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.
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.
Upvotes: 4
Reputation: 9698
NSNumber
is a toll-free bridged type to the underlying CFNumber. The documentation explicitly say that:
CFNumber objects are not intended as a replacement for C scalar values and should not be used in APIs or implementations where scalar values are more appropriate and efficient.
So it is other way round. It is recommended NOT to use NSNumber
except when needed. The documentation hints that it is primarily used for Cocoa property list and collection e.g. NSArray
Upvotes: 3
Reputation: 53010
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
:
NSArray
.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
:
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.
Upvotes: 3
Reputation: 9944
I generally go with objects when the value can be nil
, otherwise I use primitive types (unless some API needs objects).
Upvotes: 1