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);
}];