oc语言--NSValue


实际上NSMunber是NSValue的子类,NSValue可以包装任意一个对象,可以用NSValue将struct存到NSArray和NSDictionary中。

 

1+ (NSValue *)valueWithBytes:(const void *)value objCType:(const char *)type;

创建一个NSValue

value:对象地址

objCType:通常是一个用来描述对象类型和大小的字符串,@encode可以接受一个数据类型的名称自动生成一个合适的描述字符串

 

2- (void)getValue:(void *)value(出参);

从接受value的对象中

提取数值

提取的数值,存放在这个指针所指向的内存块里。

 

3Cocoa提供了常用struct数据类型转换成NSValue的便捷方法:

+ (NSValue *)valueWithPoint:(NSPoint)point;

+ (NSValue *)valueWithSize:(NSSize)size;

+ (NSValue *)valueWithRect:(NSRect)rect;

- (NSPoint)pointValue;

- (NSSize)sizeValue;

- (NSRect)rectValue;

[cpp] view plain copy

1.  //声明并初始化一个struct  

2.  NSRect rtc = NSMakeRect(12, 32, 433, 343);  

3.  //建一个NSValue  

4.  //value:象地址  

5.  //objCType:通常是一个用来描述象类型和大小的字符串,@encode会自生成一个合适的描述字符串  

6.  NSValue *value = [NSValue valueWithBytes:&rtc objCType:@encode(NSRect)];  

7.  //value添加到数  

8.  NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];  

9.  [array addObject:value];  

10.   

11. NSRect rt;  

12. //从数中取到NSValue,因只添加了一个,所以小0  

13. NSValue *v = [array objectAtIndex:0];  

14. //value中取得一个NSRect,虽然返回void,但其是它是利用指返回  

15. [v getValue:&rt];  

16. //  

17. NSLog(@"%f %f %f %f", rt.origin.x, rt.origin.y, rt.size.height, rt.size.width);  

18.   

19. //用快速枚arrayNSValuestruct属性的  

20. for(NSValue *v in array)  

21. {  

22.     NSRect rt;  

23.     [v getValue:&rt];  

24.     NSLog(@"%f %f %f %f", rt.origin.x, rt.origin.y, rt.size.height, rt.size.width);  

25. }  

26.   

27.   

28. /便捷的struct转换NAValue方式  

29. //声明并初始化一个struct  

30. NSRect rtc1 = NSMakeRect(100, 200, 300, 400);  

31. //建一个NSValue  

32. NSValue *value1 = [NSValue valueWithRect:rtc1];  

33. //value1添加到数  

34. NSMutableArray *array1 = [NSMutableArray arrayWithCapacity:10];  

35. [array1 addObject:value1];  

36. NSRect rt1 = [value1 rectValue];  

37. //  

38. NSLog(@"%f %f %f %f", rt1.origin.x, rt1.origin.y, rt1.size.height, rt1.size.width);  

自定义类型

[cpp] view plain copy

1.  typedef struct  

2.  {  

3.      int    id;  

4.      float  height;  

5.      unsigned char   flag;  

6.  } MyTestStruct;  

7.    

8.  MyTestStruct myTestSturct;  

9.  myTestSturct.id = 1;  

10. myTestSturct.height = 23.0;  

11. myTestSturct.flag = 'A';  

12. //封装数据  

13. NSValue *value = [NSValue valueWithBytes:&myTestSturct objCType:@encode(MyTestStruct)];  

14. //取出value中的数据  

15. MyTestStruct  theTestStruct;  

16.   

17. [value getValue:&theTestStruct];//theTestStruct操作取得其中的数  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值