Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use NSNumber instead of basic C number types?

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?

like image 382
Fábio Perez Avatar asked Feb 18 '11 20:02

Fábio Perez


People also ask

What is NSNumber in Objective C?

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 .

Is NSInteger primitive?

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.

What is __ NSCFNumber?

NSCFNumber is a concrete, "private" implementation of a class in that cluster.


2 Answers

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).

like image 92
BoltClock Avatar answered Nov 11 '22 08:11

BoltClock


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.

like image 20
mouviciel Avatar answered Nov 11 '22 08:11

mouviciel