一、NSValue的基本概念
- NSNumber是NSValue的子類,但NSNumber只能包裝數(shù)字類型
- NSValue可以包裝任意值結構體
二、NSValue的常見的包裝
- 為了方便結構體和NSValue的轉換,F(xiàn)oundation提供了以下方法
- 將結構體包裝成NSValue對象
- +(NSValue *)valueWithPoint: (NSPoint)point;
- +(NSValue *)valueWithSize: (NSSize)Size;
- +(NSValue *)valueWithRect: (NSRect)Rect;
CGPoint point = NSMakePoint(11,22);
NSValue *value = [NSValue valueWithPoint:point];
NSArray *arr = @[value];
- 從NSValue對象取出之前包裝的結構體
- -(NSPoint)pointValue;
- -(NSSize)SizeValue;
- -(NSRect)RectValue;
三、任意數(shù)據(jù)的包裝
-
NSValue提供了下列方法來包裝任意數(shù)據(jù)
- +(NSValue)valueWithBytes: (const void)value objCType: (const char *)type;
NSValue *pValue = [NSValue valueWithBytes:&p objCType:@encode(Person)];- value參數(shù):所包裝數(shù)據(jù)的地址
- type:用來描述這個數(shù)據(jù)類型的字符串,用@encode指令來生成
-
從NSValue中取出所包裝的數(shù)據(jù)
- -(void)getValue: (void *)value;
valueWithBytes:接收一個指針,需要傳遞需要包裝的結構體的變量的地址&p
objCType: 需要傳遞需要包裝的數(shù)據(jù)類型@encode(Person)
typedef struct{
int age;
char *name;
double height;
}Person;
Person p = {30, "lnj", 1.75};
NSValue *pValue = [NSValue valueWithBytes:&p objCType:@encode(Person)];
NSArray *arr = @[pValue];
NSLog(@"%@", arr);
// 從NSValue中取出自定義的結構體變量
Person res;
[pValue getValue:&res];
NSLog(@"age = %i, name = %s, height = %f", res.age, res.name, res.height);
- 從NSValue中取出自定義的結構體變
- 從pValue中取出然后,賦值給res地址的結構體
// 從NSValue中取出自定義的結構體變量
Person res;
[pValue getValue:&res];
NSLog(@"age = %i, name = %s, height = %f", res.age, res.name, res.height);