< Objective-C >Foundation-NSNumber

作用:将基本类型数据封装成对象,便于集合调用


创建方法:
+(NSNumber*)numberWithChar:(char)value;
+(NSNumber*)numberWithInt:(int)value;
+(NSNumber*)numberWithFloat:(float)value;
+(NSNumber*)numberWithBool:(BOOL)value;
获取数据:
(char)charValue;
(int)intValue;
(float)floatValue;
(BOOL)boolValue;
(NSString*)stringValue;

//装箱:基础类型->对象类型
NSMutableArray *array = [[NSMutableArray alloc]init];
NSNumber *numberInt = [NSNumber numberWithInt:1];
[array addObject:numberInt];
        
//拆箱:对象类型->基础类型
NSNumber *num = [array objectAtIndex:0];
NSLog(@"%d",[num intValue]);


int,NSInteger,NSUinteger,NSNumber的区别
int:c语言中的整型
NSInteger:Cocoa中新的整型,不用考虑设备是32位还是64位
NSUinteger:NSInteger的无符号类型
int,NSInteger,NSUinteger是基本数据类型,NSNumber是对象类型

NSValue:NSNumber的父类,将基本数据类型和自定义数据类型(包括指针和结构体等)封装成对象

系统结构体(以Range为例)

NSRange range1;
range1.location = 3;
range1.length = 5;
NSValue *rangeValue = [NSValue valueWithRange:range1];
        
NSRange range2;
range2 = [rangeValue rangeValue];
NSLog(@"%ld,%ld",range2.location,range2.length);

自定义结构体

//自定义结构体MyPoint
typedef struct _MyPoint {
    int x;
    int y;
}MyPoint;
//MyPoint->NSValue
MyPoint point1;
point1.x = 5;
point1.y = 6;
NSValue *pointValue = [NSValue valueWithBytes:&point1 objCType:@encode(MyPoint)];

MyPoint point2;
[pointValue getValue:&point2];
NSLog(@"%d,%d",point2.x,point2.y);

关键字@encode():

Objective-C的数据类型,甚至自定义类型,函数或方法的元类型,都可以使用ascll编码。@encode(aType)返回数据类型的c字符串(char *)的表示

NSNull:null值的对象类型,用于在集合中存放null值

//NSNull对象只有一个null值
[NSNull null];
原文地址:https://www.cnblogs.com/aY-Wonder/p/4560519.html