处理自定义结构体类型,方法
1
2
3
|
+ (NSValue *)valueWithBytes:( const void *)value objCType:( const char *)type - (id)initWithBytes:( const void *)value objCType:( const char *)type - ( void )getValue:( void *)buffer |
typedef struct {
int id,
float height,
unsigned char flag
}MyTestStruct;
此时,我们就可以使用MyTestStruct这个结构体来很容易地封装数据。如
MyTestStruct myTestStruct;
myTestStruct.id=1;
myTestStruct.height=23.0;
myTestStruct.flag='A';
NSValue *value = [NSValue valueWithBytes:&myTestStruct objCType:@encode(MyTestStruct)];
在我们想取出*value 中的数据时,可以使用如下方式:
MyTestStruct theTestStruct;
[valeu getValue:&theTestStruct];
之后就可以对theTestStruct的操作来取得其中的数据。
1
2
|
+ (NSValue *)valueWithRange:(NSRange)range - (NSRange)rangeValue |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
NSRange rangeA ; rangeA.location = 0 ; rangeA.location = 10 ; // 创建NSRange的值对象 NSValue *rangeValue = [NSValue valueWithRange:rangeA] ; // 重新获取值对象包含的值 NSRange rangeB = [rangeValue rangeValue] ; NSLog(@ "%d,%d" ,rangeB.location , rangeB.length) ; // 10,10 |
NSValue包装对象指针,CGRect结构体等
@interface NSValue (NSValueUIGeometryExtensions)
+ (NSValue *)valueWithPointer:(const void *)pointer;//保存对象指针
+ (NSValue *)valueWithCGPoint:(CGPoint)point;//保存CGPoint结构体
+ (NSValue *)valueWithCGSize:(CGSize)size;//保存CGSize结构体
+ (NSValue *)valueWithCGRect:(CGRect)rect;//保存CGRect结构体
+ (NSValue *)valueWithCGAffineTransform:(CGAffineTransform)transform;
+ (NSValue *)valueWithUIEdgeInsets:(UIEdgeInsets)insets;
- (void *)pointerValue;
- (CGPoint)CGPointValue;
- (CGSize)CGSizeValue;
- (CGRect)CGRectValue;
- (CGAffineTransform)CGAffineTransformValue;
- (UIEdgeInsets)UIEdgeInsetsValue;
@end
2 3
4
5
6
7
8
9
|
CGPoint origin = CGPointMake(10.0 , 10.0) ; NSValue *ptValue = [NSValue valueWithCGPoint:origin] ; NSArray *ptArr = [NSArray arrayWithObject:ptValue]; NSValue *ptValueB = [ptArr objectAtIndex:0] ; CGPoint originB = [ptValueB CGPointValue] ; |