实际上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的对象中
提取数值
提取的数值,存放在这个指针所指向的内存块里。
3、Cocoa提供了常用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. //用快速枚举遍历array并输出NSValue中struct属性的值
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操作取得其中的数据