OC中的NSValue

来源:互联网 发布:如何备份c盘数据 编辑:程序博客网 时间:2024/05/29 11:18

一种是系统自带的

封装:

      //点        NSPoint point = NSMakePoint(2, 3);        NSValue *value1 = [NSValue valueWithPoint:point];        NSLog(@"%@",value1);

解封装:

        //解析了系统的        NSPoint newpoint = value1.pointValue;        NSLog(@"x = %.2f, y = % .2f",newpoint.x,newpoint.y);


运行结果:

2014-12-20 12:52:06.321谭启宏-OC-3[2329:695553] NSPoint: {2, 3}

2014-12-20 12:52:06.322谭启宏-OC-3[2329:695553] x = 2.00, y =  3.00

Program ended with exit code: 0



另一种(首先要定义一个结构体)

typedef struct {    NSInteger num;    NSInteger score;}Student;

然后

封装:

        //结构体        Student student =  {2,10};        NSValue *value2 = [NSValue valueWithBytes:&student objCType:@encode(Student)];        NSLog(@"%@",value2);

解封装:

        //解封装自定义的                Student newstudent ;        [value2 getValue:&newstudent];        //输出的时候用数据输出        NSLog(@" num = %ld, score = %ld ",newstudent.num,newstudent.score);

运行结果:

2014-12-20 12:53:25.736谭启宏-OC-3[2352:704124] <02000000 00000000 0a000000 00000000>

2014-12-20 12:53:25.737谭启宏-OC-3[2352:704124]  num = 2, score = 10 

Program ended with exit code: 0



后话:

        结构体不能直接存入数组

        我们可以通过Value把结构体封装成对象存到数组中(数组可以存对象)

0 0
原创粉丝点击