一. NSNumber:用于把C语言的数值型包装成对象
要把C语言的数值和结构体添加到OC集合中,就必须先包装成对象。
//把C语言的数值型包装成对象
NSNumber *number1 = [NSNumber numberWithBool:YES];
NSNumber *number2 = [NSNumber numberWithChar:'A'];
NSNumber *number3 = [NSNumber numberWithInt:100];
NSNumber *number4 = [NSNumber numberWithFloat:3.4f];
NSNumber *number5 = @99;
NSNumber *number6 = @('B');
NSNumber *number7 = @11.1;
NSLog(@"%@ %@ %@ %@ %@ %@ %@",number1,number2,number3,number4,number5,number6,number7);
//NSNumber变量转换成C语言数值
int num1 = number1.intValue;
int num2 = [number2 intValue];
float num3 = number4.floatValue;
NSLog(@"%d %d %.2f",num1,num2,num3);
二. NSValue:把结构体包装成对象
//利用NSValue包装常用的结构体
NSValue *value1 = [NSValue valueWithRange:NSMakeRange(3, 10)];
NSValue *value2 = [NSValue valueWithSize:NSMakeSize(100, 111)];
NSLog(@"%@ %@",value1,value2);
typedef struct {
char *name;
int age;
}Person;
Person per = {"xiaoming",20};
//利用NSValue包装自定义的结构体
NSValue *perValue = [NSValue valueWithBytes:&per objCType:@encode(Person)];
//NSValue变量转换成结构体
NSRange range = [value1 rangeValue];
NSSize size = [value2 sizeValue];
Person per1;
[perValue getValue:&per1];
NSLog(@"location = %lu height = %.0f name = %s",range.location,size.height,per1.name);