1、常見(jiàn)結(jié)構(gòu)體的儲(chǔ)存
比較常見(jiàn)的結(jié)構(gòu)體:CGPoint? ,CGSize,CGRect。。。。。。我們?nèi)绾未娣诺綌?shù)組中呢?因?yàn)槭墙Y(jié)構(gòu)體不是對(duì)象,不能添加到數(shù)組中,解決方法:把這些常見(jiàn)的結(jié)構(gòu)裝換成對(duì)象,讓后放進(jìn)去,取出來(lái)在裝換成結(jié)構(gòu)體使用。我們想到了NSValue使用方法如下:
CGPoint point = CGPointMake(0, 0);
NSMutableArray *array = [[NSMutableArray alloc]initWithCapacity:0];
NSValue *value = [NSValue valueWithCGPoint:point];
[array addObject:value];
取出數(shù)組之后的對(duì)象的使用:
NSValue *tmpValue = array[0];
CGPoint tmpPoint = [tmpValue CGPointValue];
下面是一些常見(jiàn)的結(jié)構(gòu)體使用方法是一樣的
+ (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、自定義結(jié)構(gòu)體的存儲(chǔ)
同樣是先轉(zhuǎn)換NSValue對(duì)象再加入數(shù)組中,代碼如下:
//自定義結(jié)構(gòu)體
typedef struct Books
{
NSString *title;
NSString *author;
NSString *subject;
int? book_id;
} book;
//初始化結(jié)構(gòu)體數(shù)據(jù)
book book1 = {@"首頁(yè)",@"作者",@"子類(lèi)",1};
book book2 = {@"首頁(yè)",@"作者",@"子類(lèi)",2};
book book3 = {@"首頁(yè)",@"作者",@"子類(lèi)",3};
//存入數(shù)據(jù)
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];
//取出數(shù)據(jù)
[books enumerateObjectsUsingBlock:^(id? _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
book value;
NSValue *customValue = obj;
[customValue getValue:&value];
NSLog(@"%d",value.book_id);
}];