代码改变世界

_int、NSInteger、NSUInteger、NSNumber的区别和联系

2015-12-28 21:58  JG2014  阅读(315)  评论(0编辑  收藏  举报

1、首先先了解下NSNumber类型:

苹果官方文档地址:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html

NSNumber是NSValue的一个子类,它是一个对象来存储数字值包括bool型,它提供了一系列的方法来存储char a signed or unsigned char, short int, int, long int, long long int, float, or double or as a BOOL,它提供了一个compare:方法来决定两个NSNumber对象的排序;

创建一个NSNumber对象有以下方法:

 

[objc] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. + numberWithBool:  
  2. + numberWithChar:  
  3. + numberWithDouble:  
  4. + numberWithFloat:  
  5. + numberWithInt:  
  6. + numberWithInteger:  
  7. + numberWithLong:  
  8. + numberWithLongLong:  
  9. + numberWithShort:  
  10. + numberWithUnsignedChar:  
  11. + numberWithUnsignedInt:  
  12. + numberWithUnsignedInteger:  
  13. + numberWithUnsignedLong:  
  14. + numberWithUnsignedLongLong:  
  15. + numberWithUnsignedShort:  


初始化方法:

 

 

[objc] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1.  initWithBool:  
  2.  initWithChar:  
  3.  initWithDouble:  
  4.  initWithFloat:  
  5.  initWithInt:  
  6.  initWithInteger:  
  7.  initWithLong:  
  8.  initWithLongLong:  
  9.  initWithShort:  
  10.  initWithUnsignedChar:  
  11.  initWithUnsignedInt:  
  12.  initWithUnsignedInteger:  
  13.  initWithUnsignedLong:  
  14.  initWithUnsignedLongLong:  
  15.  initWithUnsignedShort:  

检索

 

 

[objc] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. – boolValue  
  2. – charValue  
  3. – decimalValue  
  4. – doubleValue  
  5. – floatValue  
  6. – intValue  
  7. – integerValue  
  8. – longLongValue  
  9. – longValue  
  10. – shortValue  
  11. – unsignedCharValue  
  12. – unsignedIntegerValue  
  13. – unsignedIntValue  
  14. – unsignedLongLongValue  
  15. – unsignedLongValue  
  16. – unsignedShortValue  

NSNumber类型有点类似id类型,对于任何类型的数字对象都能用它来声明,也就是用它来声明数字对象,通过声明,很难判断声明变量是什么数字类型,确定数字对象类型多是在初始化的时候才能确定。

 

数字对象的创建或者初始化:

格式:

NSNumber 数字对象 = [NSNumber numberWith数字类型:数值];

 

[objc] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. intNumber = [NSNumber numberWithInt:100];  
  2. longNumber = [NSNumber numberWithLong:0xabcdef];  
  3. floatNumber = [NSNumber numberWithFloat:10.01];  


2、int、 NSInteger、 NSUInteger、NSNumber之间的区别和联系

 

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

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

NSInteger是基础类型,NSNumber是一个类,如果需要存储一个数值,直接使用NSInteger是不行的,比如在一个数组里使用下面的语句就会报错:

 

[objc] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. NSArray *array = [NSArray alloc] init];  
  2. [array addObject:3];  

因为array里应该是一个类,但‘3’不是,所以需要用NSNumber:

 

 

[objc] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. NSArray *array = [NSArray alloc] init];  
  2. [array addObject:[NSNumber numberWithInt:3]];  


写的比较简单,希望有帮助