NSValue
2019-12-11 本文已影响0人
笨鸟后飞了
NSValue除了能够包装NSNumber能够包装的基础数字类型外,还能够包装系统框架提供的CGRect/CGPoint/CGSize等数据结构,也可以是自己定义的struct。最终也能放入数组。
1、封装方法:
+ (NSValue )valueWithBytes:(const void )value objCType:(const char *)type;
2、解封方法:
- (void)getValue:(void *)value;
代码示例:
//声明一个NSRange结构体
NSRange range = {9,1};
//把NSRange结构体快速的转换成为OC的对象
NSValue *value = [NSValue valueWithRange:range];
NSLog(@"NSValue = %@",value);
//把Value对象转换回NSRange结构体
NSRange result0Range = [value rangeValue];
// NSRange result0Range = value.rangeValue;
NSLog(@"location = %ld length = %ld",result0Range.location,result0Range.length);
//自定义一个结构体
struct cat {
NSInteger weight;
};
//实例化一个struct cat
struct cat myCat = {900};
//把自定义的结构体转换成为NSValue
//参数1: 所转化结构体的地址
//参数2: 转化类型所对应的C字符串(@encode(待转化类型))
NSValue *catValue = [NSValue value:&myCat withObjCType:@encode(struct cat)];
NSLog(@"catValue = %@",catValue);
//NSValue转换回自定义结构体
//实例化一个接收的实体
struct cat myCat1;
//需要接收实体的地址
[catValue getValue:&myCat1];
NSLog(@"myCat1.weight = %ld",myCat1.weight);
//使用结构体指针
struct cat *pCat = malloc(sizeof(struct cat));
pCat -> weight =10;
//转换为NSValue
NSValue *value1 = [NSValue value:pCat withObjCType:@encode(struct cat)];
//转换回自定义结构体
struct cat *pCat1 = malloc(sizeof(struct cat));
[value1 getValue:pCat1];