NSValue除了能夠包裝NSNumber能夠包裝的基礎(chǔ)數(shù)字類型外秧倾,還能夠包裝系統(tǒng)框架提供的CGRect/CGPoint/CGSize等數(shù)據(jù)結(jié)構(gòu)怨酝,也可以是自己定義的struct着憨。最終也能放入數(shù)組饭宾。
1、封裝方法:
+ (NSValue )valueWithBytes:(const void )value objCType:(const char *)type;
2有送、解封方法:
- (void)getValue:(void *)value;
代碼示例:
//聲明一個(gè)NSRange結(jié)構(gòu)體
NSRange range = {9,1};
//把NSRange結(jié)構(gòu)體快速的轉(zhuǎn)換成為OC的對(duì)象
NSValue *value = [NSValue valueWithRange:range];
NSLog(@"NSValue = %@",value);
//把Value對(duì)象轉(zhuǎn)換回NSRange結(jié)構(gòu)體
NSRange result0Range = [value rangeValue];
// NSRange result0Range = value.rangeValue;
NSLog(@"location = %ld length = %ld",result0Range.location,result0Range.length);
//自定義一個(gè)結(jié)構(gòu)體
struct cat {
NSInteger weight;
};
//實(shí)例化一個(gè)struct cat
struct cat myCat = {900};
//把自定義的結(jié)構(gòu)體轉(zhuǎn)換成為NSValue
//參數(shù)1: 所轉(zhuǎn)化結(jié)構(gòu)體的地址
//參數(shù)2: 轉(zhuǎn)化類型所對(duì)應(yīng)的C字符串(@encode(待轉(zhuǎn)化類型))
NSValue *catValue = [NSValue value:&myCat withObjCType:@encode(struct cat)];
NSLog(@"catValue = %@",catValue);
//NSValue轉(zhuǎn)換回自定義結(jié)構(gòu)體
//實(shí)例化一個(gè)接收的實(shí)體
struct cat myCat1;
//需要接收實(shí)體的地址
[catValue getValue:&myCat1];
NSLog(@"myCat1.weight = %ld",myCat1.weight);
//使用結(jié)構(gòu)體指針
struct cat *pCat = malloc(sizeof(struct cat));
pCat -> weight =10;
//轉(zhuǎn)換為NSValue
NSValue *value1 = [NSValue value:pCat withObjCType:@encode(struct cat)];
//轉(zhuǎn)換回自定義結(jié)構(gòu)體
struct cat *pCat1 = malloc(sizeof(struct cat));
[value1 getValue:pCat1];