NSValue與數據類型

NSValue可以包裝所有的數據類型,而前一篇博客寫到的NSNumber也是繼承自NSValue,在API中我們可以發現,實際上是用了分類進行了擴充,因爲集合中需要的是OC對象,所以我們使用的基本數據類型和結構體都可以使用NSValue進行包裝,再丟給集合。

 CGPoint p=CGPointMake(20, 10);

        //@encode(CGPoint)標示類型,轉換成C語言字符串

       NSValue *v= [NSValue valueWithBytes:&p objCType:@encode(CGPoint)];

        

        NSArray *aa=@[@"123456",@10.5,v];

        

        

        CGPoint p2;

        //返回的一個指針

        [aa[2] getValue:&p2];

        NSLog(@"p2==%@",NSStringFromPoint(p2));

        

        

        //系統自帶的結構體用以下方式

        NSValue *valus =[NSValue valueWithPoint:CGPointMake(20, 10)];

        [NSValue valueWithRect:CGRectMake(20, 20, 122, 300)];

        [valus pointValue];

        

        //自定義結構體包裝

        struct Student{

            int age;

        };

        struct Student su={15};

        [NSValue valueWithBytes:&su objCType:@encode(struct Student)];

        

        //typedef的方式更簡單

        typedef struct {

            int age;

        }Student2;

        Student2 stu={22};

        [NSValue valueWithBytes:&stu objCType:@encode(Student2)];


總結:

1、系統自帶的結構體類型和基本數據類型我們可以用NSValue的類方法以value開頭的方法對各類型進行包裝

2、自定義的結構體需要我們使用valueWithBytes獲取存儲結構體的地址和@encode獲取結構體的結構。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章