Objective-C:NSValue类的常见用法

特殊类型的包装类:数组、结构体(OC内部的、自定义的)、指针

 1 //
 2 //  main.m
 3 //  05-NSValue
 4 //
 5 //  Created by ma c on 15/8/17.
 6 //  Copyright (c) 2015年. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 typedef struct
11 {
12     char *name;
13     int age;
14     char gender;
15 }Student;
16 
17 int main(int argc, const char * argv[])
18 {
19     @autoreleasepool
20     {
21         //NSValue测试
22         //1.指针
23         int num = 10;
24         int *p = &num;
25         NSValue *value1 = [NSValue valueWithPointer:p];
26         int *p2 = (int*)[value1 pointerValue];
27         NSLog(@"num = %d",*(p2));
28         
29         //2.数组
30         int arr[5] = {1,2,3,4,5};
31         NSValue *value2 = [NSValue valueWithPointer:arr];
32         int *p3 = (int*)[value2 pointerValue];
33         for(int i=0; i<5; i++)
34         {
35             NSLog(@"%d",p3[i]);
36         }
37         
38         //3.Foundation中常用的结构体:NSRange\NSRect\NSSize\NSPoint
39         NSRange range = NSMakeRange(0, 5);
40         NSValue *value3 = [NSValue valueWithRange:range];
41         NSRange range2 = [value3 rangeValue];
42         NSLog(@"%@",NSStringFromRange(range2));
43         
44         NSRect rect = NSMakeRect(0, 0, 100, 100);
45         NSValue *value4 = [NSValue valueWithRect:rect];
46         NSRect rect2 = [value4 rectValue];
47         
48         NSLog(@"%@",NSStringFromRect(rect2));
49         
50         
51         //4.自定义的结构体
52         Student stu = {"Tom",20,'M'};
53         NSValue *value5 = [NSValue valueWithBytes:&stu objCType:@encode(Student)];
54         NSLog(@"%s",@encode(Student));//输出结构体类型
55         
56         Student stu2;
57         [value5 getValue:&stu2];
58         NSLog(@"name = %s,age = %i,gender = %c",stu2.name,stu2.age,stu2.gender);
59     }
60     return 0;
61 }

 

posted @ 2015-08-17 19:20  XYQ全哥  阅读(389)  评论(0编辑  收藏  举报