1、常见结构体的储存
比较常见的结构体:CGPoint ,CGSize,CGRect。。。。。。我们如何存放到数组中呢?因为是结构体不是对象,不能添加到数组中,解决方法:把这些常见的结构装换成对象,让后放进去,取出来在装换成结构体使用。我们想到了NSValue使用方法如下:
CGPoint point = CGPointMake(0, 0);
NSMutableArray *array = [[NSMutableArray alloc]initWithCapacity:0];
NSValue *value = [NSValue valueWithCGPoint:point];
[array addObject:value];
取出数组之后的对象的使用:
NSValue *tmpValue = array[0];
CGPoint tmpPoint = [tmpValue CGPointValue];
下面是一些常见的结构体使用方法是一样的
+ (NSValue *)valueWithCGPoint:(CGPoint)point;
+ (NSValue *)valueWithCGVector:(CGVector)vector;
+ (NSValue *)valueWithCGSize:(CGSize)size;
+ (NSValue *)valueWithCGRect:(CGRect)rect;
+ (NSValue *)valueWithCGAffineTransform:(CGAffineTransform)transform;
+ (NSValue *)valueWithUIEdgeInsets:(UIEdgeInsets)insets;
+ (NSValue *)valueWithUIOffset:(UIOffset)insets NS_AVAILABLE_IOS(5_0);
- (CGPoint)CGPointValue;
- (CGVector)CGVectorValue;
- (CGSize)CGSizeValue;
- (CGRect)CGRectValue;
- (CGAffineTransform)CGAffineTransformValue;
- (UIEdgeInsets)UIEdgeInsetsValue;
- (UIOffset)UIOffsetValue NS_AVAILABLE_IOS(5_0);
@end
2、自定义结构体的存储
同样是先转换NSValue对象再加入数组中,代码如下:
//自定义结构体
typedef struct Books
{
NSString *title;
NSString *author;
NSString *subject;
int book_id;
} book;
//初始化结构体数据
book book1 = {@"首页",@"作者",@"子类",1};
book book2 = {@"首页",@"作者",@"子类",2};
book book3 = {@"首页",@"作者",@"子类",3};
//存入数据
NSValue *customValue1 = [NSValue valueWithBytes:&book1 objCType:@encode(struct Books)];
NSValue *customValue2 = [NSValue valueWithBytes:&book2 objCType:@encode(struct Books)];
NSValue *customValue3 = [NSValue valueWithBytes:&book3 objCType:@encode(struct Books)];
NSMutableArray *books = [NSMutableArray arrayWithObjects:customValue1,customValue2,customValue3, nil];
//取出数据
[books enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
book value;
NSValue *customValue = obj;
[customValue getValue:&value];
NSLog(@"%d",value.book_id);
}];