您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页Foundaton框架-->NSValue

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);

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务