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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With