iOS开发之int,NSInteger,NSUInteger,NSNumber的使用

转自:http://chensmiles.blog.163.com/blog/static/121463991201296101228806/


If you’ve ever found yourself scratching your head thinking “now which one should I be using, NSNumber or NSInteger?” the short summary below should help.

NSInteger is nothing more than a synonym for a long integer. What follows is how NSInteger is defined:

1 2 3 4 5 6 7 
#if __LP64__ || NS_BUILD_32_LIKE_64   typedef long NSInteger;   typedef unsigned long NSUInteger; #else   typedef int NSInteger;   typedef unsigned int NSUInteger; #endif

NSNumber is an Objective-C class, a subclass of NSValue to be specific. You can create an NSNumber object from a signed or unsigned char, short int, int, long int, long long int, float, double or BOOL.

One of the primary distinctions is that you can use NSNumber in collections, such as NSArray, where an object is required. For example, if you need to add a float into an NSArray, you would first need to create an NSNumber object from the float:

1 2 3 4 
float percentage = 40.5; ... // Create NSNumber object, which can now be inserted into an NSArray NSNumber *percentageObject = [NSNumber numberWithFloat:percentage];

NSInteger is a simply an integer, NSNumber is an object.

以上转至:http://mobiledevelopertips.com/cocoa/nsnumber-and-nsinteger.html



附录:

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 

typedef long NSInteger;

#else

typedef int NSInteger;

#endif


这篇介绍几种变量类型的区别和注意点,虽然简单.但比较实用.

1、当需要使用int类型的变量的时候,可以像写C的程序一样,用int,也可以用NSInteger,但更推荐使用NSInteger,因为这样就不用考虑设备是32位的还是64位的。

2、NSUInteger是无符号的,即没有负数,NSInteger是有符号的。

3、有人说既然都有了NSInteger等这些基础类型了为什么还要有NSNumber?它们的功能当然是不同的。

NSInteger是基础类型,但是NSNumber是一个类。如果想要存储一个数值,直接用NSInteger是不行的,比如在一个Array里面这样用:

NSArray *array= [[NSArray alloc]init];
[array addObject:3];//会编译错误

这样是会引发编译错误的,因为NSArray里面放的需要是一个类,但‘3’不是。这个时候需要用到NSNumber:

NSArray *array= [[NSArray alloc]init];
[array addObject:[NSNumber numberWithInt:3]];

Cocoa提供了NSNumber类来包装(即以对象形式实现)基本数据类型。

例如以下创建方法:

+ (NSNumber*)numberWithChar: (char)value;
+ (NSNumber*)numberWithInt: (int)value;
+ (NSNumber*)numberWithFloat: (float)value;
+ (NSNumber*)numberWithBool: (BOOL) value;

将基本类型数据封装到NSNumber中后,就可以通过下面的实例方法重新获取它:

- (char)charValue;
- (int)intValue;
- (float)floatValue;
- (BOOL)boolValue;
- (NSString*)stringValue;




#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
这是NSInteger的定义
对于不同平台32,64位有不同的最大值(int long)。
可以直接转化。
所以mac os或者ios上的系统api都是使用NSInteger作为参数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值