What is the benefit of using NSNumber from Foundation Framework instead of basic C types (int, float, double)?
Using NSNumber:
NSNumber *intNumber;
NSInteger myInt;
intNumber = [NSNumber numberWithInteger: 100];
myInt = [intNumber integerValue];
Using pure C:
int intNumber;
intNumber = 100;
Seems a lot easier and economic to use C.
I know NSNumber is an object (or class?) type, but why would I use them instead simple C variables? When should I use them?
NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .
It is not a C primitive (like int, unsigned int, float, double, etc.) NSInteger , CGFloat , NSUInteger are simple typedefs over the C primitives. The need for NSNumber arises from the need to use numbers as parameters to APIs that require Objects.
NSCFNumber is a concrete, "private" implementation of a class in that cluster.
The purpose of NSNumber
is simply to box primitive types in objects (pointer types), so you can use them in situations that require pointer-type values to work.
One common example: you have to use NSNumber
if you want to persist numeric values in Core Data entities.
You can and should use primitives for calculations (unless with decimals, in which case you use NSDecimal
or NSDecimalNumber
).
If you need to pass a number as an object, use NSNumber
.
If you need to make arithmetic operations, you can use int
and double
. If you don't want to bother with 32/64 bit issues, you can use NSInteger
and CGFloat
.
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