Foundaton框架-->NSValue

一、NSValue的基本概念

  • NSNumber是NSValue的子类,但NSNumber只能包装数字类型
  • NSValue可以包装任意值结构体

二、NSValue的常见的包装

  • 为了方便结构体和NSValue的转换,Foundation提供了以下方法
  • 将结构体包装成NSValue对象
    • +(NSValue *)valueWithPoint: (NSPoint)point;
    • +(NSValue *)valueWithSize: (NSSize)Size;
    • +(NSValue *)valueWithRect: (NSRect)Rect;
CGPoint point = NSMakePoint(11,22);
NSValue *value = [NSValue valueWithPoint:point];
NSArray *arr = @[value];
  • 从NSValue对象取出之前包装的结构体
    • -(NSPoint)pointValue;
    • -(NSSize)SizeValue;
    • -(NSRect)RectValue;

三、任意数据的包装

  • NSValue提供了下列方法来包装任意数据

    • +(NSValue)valueWithBytes: (const void)value objCType: (const char *)type;
    NSValue *pValue = [NSValue valueWithBytes:&p objCType:@encode(Person)];
    
    • value参数:所包装数据的地址
    • type:用来描述这个数据类型的字符串,用@encode指令来生成
  • 从NSValue中取出所包装的数据

    • -(void)getValue: (void *)value;
  • valueWithBytes:接收一个指针,需要传递需要包装的结构体的变量的地址&p

  • objCType: 需要传递需要包装的数据类型@encode(Person)

 typedef struct{
        int age;
        char *name;
        double height;
    }Person;
    Person p = {30, "lnj", 1.75};
    NSValue *pValue = [NSValue valueWithBytes:&p objCType:@encode(Person)];
    NSArray *arr = @[pValue];
    NSLog(@"%@", arr);
    // 从NSValue中取出自定义的结构体变量
    Person res;
    [pValue getValue:&res];
    NSLog(@"age = %i, name = %s, height = %f", res.age, res.name, res.height);
  • 从NSValue中取出自定义的结构体变
    • 从pValue中取出然后,赋值给res地址的结构体
    // 从NSValue中取出自定义的结构体变量
    Person res;
    [pValue getValue:&res];
    NSLog(@"age = %i, name = %s, height = %f", res.age, res.name, res.height);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容