开发者

Should I use NSNumber instead of basic C number types?

开发者 https://www.devze.com 2023-02-11 19:00 出处:网络
What is the benefit of using NSNumber from Founda开发者_开发知识库tion Framework instead of basic C types (int, float, double)?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消