Objective-C NSValue类的常用方法

NSValue类是OC中用来存储任意值的容器,是NSNumber的父类,NSNumber类是用来封装基本数据类型的

初始化方法:

- (instancetype)initWithBytes:(const void *)value
                     objCType:(const char *)type
//便利构造器方法
+ (NSValue *) valueWithBytes:(const void *)value
                   objCType:(const char *)type

第一个参数为要封装的变量的地址,第二个参数用来描述该数据类型的字符串,可以用@encode编译器指令自动生成该字符串

用法:

//自定义结构体类型Student
typedef struct student{
        char name[50];
        char sex[2];
        NSInteger age;
        NSInteger grade;
        char number[50];
    }Student;
//创建结构体stu
Student stu = {"smithjackyson","男",23,98,"3112006304"};
//创建NSValue实例value存储stu
NSValue *value = [[NSValue alloc] initWithBytes:&stu objCType:@encode(Student)];
NSValue *value1 = [NSValue valueWithBytes:&stu objCType:@encode(Student)];

获取value中存储的对象如下:

//定义一个新结构体变量stu1
Student stu1;
//将value中存储的结构体赋值给stu1
[value getValue:&stu1];

判断两个NSvalue存储的对象是否相同

- (BOOL)isEqualToValue:(NSValue *)aValue

存储各种类型的便利构造器和属性,以及获取对应值的方法:

+ (NSValue *)valueWithRange:(NSRange)range
@property(readonly) NSRange rangeValue

+ (NSValue *)valueWithCGPoint:(CGPoint)point
- (CGPoint)CGPointValue

+ (NSValue *)valueWithCGVector:(CGVector)vector
- (CGVector)CGVectorValue

+ (NSValue *)valueWithCGSize:(CGSize)size
- (CGSize)CGSizeValue

+ (NSValue *)valueWithCGRect:(CGRect)rect
- (CGRect)CGRectValue

+ (NSValue *)valueWithPointer:(const void *)aPointer
@property(readonly) void *pointerValue

+ (NSValue *)valueWithNonretainedObject:(id)anObject
@property(readonly) id nonretainedObjectValue

+ (NSValue *)valueWithCGAffineTransform:(CGAffineTransform)transform
- (CGAffineTransform)CGAffineTransformValue

+ (NSValue *)valueWithUIEdgeInsets:(UIEdgeInsets)insets
- (UIEdgeInsets)UIEdgeInsetsValue

+ (NSValue *)valueWithUIOffset:(UIOffset)insets
- (UIOffset)UIOffsetValue

+ (NSValue *)valueWithCATransform3D:(CATransform3D)aTransform
@property(readonly) CATransform3D CATransform3DValue

+ (NSValue *)valueWithCMTime:(CMTime)time
@property(readonly) CMTime CMTimeValue

+ (NSValue *)valueWithCMTimeRange:(CMTimeRange)timeRange
@property(readonly) CMTimeRange CMTimeRangeValue

+ (NSValue *)valueWithCMTimeMapping:(CMTimeMapping)timeMapping
@property(readonly) CMTimeMapping CMTimeMappingValue

+ (NSValue *)valueWithMKCoordinate:(CLLocationCoordinate2D)coordinate
@property(readonly) CLLocationCoordinate2D MKCoordinateValue

+ (NSValue *)valueWithMKCoordinateSpan:(MKCoordinateSpan)span
@property(readonly) MKCoordinateSpan MKCoordinateSpanValue

+ (NSValue *)valueWithSCNVector3:(SCNVector3)vector
@property(nonatomic, readonly) SCNVector3 SCNVector3Value

+ (NSValue *)valueWithSCNVector4:(SCNVector4)vector
@property(nonatomic, readonly) SCNVector4 SCNVector4Value

+ (NSValue *)valueWithSCNMatrix4:(SCNMatrix4)
@property(nonatomic, readonly) SCNMatrix4 SCNMatrix4Value

 

 


转载请注明:作者SmithJackyson

posted @ 2015-12-19 16:16  SmithJackyson  阅读(760)  评论(0编辑  收藏  举报