What is the benefit of using NSNumber from Founda开发者_开发知识库tion 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?
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
.
Because with dealing with passing of parameters with certain objects, using a basic data type will not work. Also, the NSNumber class gives you options for converting values into other datatypes quickly.
精彩评论